chachew Posted November 16, 2012 Share Posted November 16, 2012 So i am trying to get a list of items out of my MySql database but my loop is not creating the array correctly, its dropping multiple rows when the key is the same name. <?php $search = 'item1'; $con = require_once('./dbconnect.php'); mysql_select_db("packages", $con); $package = mysql_query("SELECT * FROM $search", $con); while($item = mysql_fetch_row($package)){ $arr[$item[1]] = array('description' => $item[2], 'image' => $item[3]); } echo json_encode($arr); mysql_close($con); ?> So the loop works and does actually create the array with the various 'packages' in their respective array. The issue that i am having is that mysql_fetch_row($package)) can and will contain multiple keys that are the same name but with different things in the array. For example, the database will be something like this: PACK LEV DESCRIPTION IMAGES item1 A1 description for stuff1 image1 item1 A2 description for more stuff image2 item1 B1 more stuff here image3 item2 A1 description here for item2 image1 item2 B1 description contents here image2 --------------------------------------------------------------------------------- My Above code will produce an array like this: Array ( [item1] => Array ( [description] => more stuff here [image] => image3 ) [item2] => Array ( [description] => description contents here [image] => image2 ) ) What i want the array to be is: Array ( [item1] => Array ( [A1] => Array ( [description] => description for stuff1 [image] => image1 ) [A2] => Array ( [description] => description for more stuff [image] => image2 ) [b1] => Array ( [description] => more stuff here [image] => image3 ) [item2] => Array ( [A1] => Array ( [description] => description here for item2 [image] => image1 ) [b1] => Array ( [description] => description contents here [image] => image2 ) ) ) I hope this makes sense..Thanks for looking Quote Link to comment https://forums.phpfreaks.com/topic/270763-mysql_query-loop-into-multidimensional-array/ Share on other sites More sharing options...
Barand Posted November 16, 2012 Share Posted November 16, 2012 while($item = mysql_fetch_row($package)){ $arr[$item[0]][$item[1]] = array('description' => $item[2], 'image' => $item[3]); } Quote Link to comment https://forums.phpfreaks.com/topic/270763-mysql_query-loop-into-multidimensional-array/#findComment-1392807 Share on other sites More sharing options...
chachew Posted November 16, 2012 Author Share Posted November 16, 2012 Brilliant! Exactly what i've been banging my head against the wall to achieve Quote Link to comment https://forums.phpfreaks.com/topic/270763-mysql_query-loop-into-multidimensional-array/#findComment-1392838 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.