Jump to content

Array problem :)


forumnz

Recommended Posts

How can I separate these sets of data in this array so that they can be inserted into a database?

 

Array ( [0] => stdClass Object ( [field1] => a [field2] => b ) [1] => stdClass Object ( [field1] => a2 [field2] => b2  ) ) 

 

Would I use the [0] and [1]? Sorry for the question, but if someone can point me in the right direction I am more than happy to try to work it out for myself :)

 

Thank you :)

Link to comment
https://forums.phpfreaks.com/topic/157305-array-problem/
Share on other sites

Not quite understand the structure of your array.

But if you wished to use array to insert data into database, i would suggest use this:

 

array(
  'field_1' => 'value_1',
  'field_2' => 'value_2',
  ... so on...
);

So the key of the array will be your field name and the value is the field's value.

 

So you probably need a function that will dispatch this array and construct a sql.

 

function insert($data) {
  $sql = "INSERT INTO `table_name` ";
  $key = "";
  $val = "";
  
  foreach($data as $field=>$value) {
    $key .= "`$field`";
    $val .= "'$value'";
    
    if($value != end($data)) {
        $key .= ", ";
        $val .= ", ";
    }
  }

  $sql .= "($key) VALUES ($val);";

  mysql_query($sql) or die(mysql_error());
}

 

Hope this give you some idea.  ;)

Link to comment
https://forums.phpfreaks.com/topic/157305-array-problem/#findComment-829116
Share on other sites

Erm.. I assumed each object is a column in your database. So field1 will be your field name and field2 is your value.

 

try:

 

$tmp_arry = array();
foreach($your_array $as $arry) {
    $field = $arry->field1;
    $value = $arry->$field2;

    $tmp_arry[$field] = $value;
}

print_r($tmp_arry);

Link to comment
https://forums.phpfreaks.com/topic/157305-array-problem/#findComment-829128
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.