forumnz Posted May 8, 2009 Share Posted May 8, 2009 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 More sharing options...
xenophobia Posted May 8, 2009 Share Posted May 8, 2009 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 More sharing options...
forumnz Posted May 8, 2009 Author Share Posted May 8, 2009 Thanks xenophobia - it helps a lot. How can I rearrange the output to suit? Currently it is: Array ( [0] => stdClass Object ( [field1] => a [field2] => b ) [1] => stdClass Object ( [field1] => a2 [field2] => b2 ) ) Thanks Link to comment https://forums.phpfreaks.com/topic/157305-array-problem/#findComment-829118 Share on other sites More sharing options...
xenophobia Posted May 8, 2009 Share Posted May 8, 2009 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 More sharing options...
Ken2k7 Posted May 8, 2009 Share Posted May 8, 2009 forumnz, Say that object is stored in $obj. var_dump($obj->{'field1'}); Link to comment https://forums.phpfreaks.com/topic/157305-array-problem/#findComment-829133 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.