Jump to content


Photo

Mysql_Query Loop Into Multidimensional Array

mysql_query array multidimensional array json_encode

  • Please log in to reply
2 replies to this topic

#1 chachew

chachew

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 15 November 2012 - 07:04 PM

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

#2 Barand

Barand

    Sen . ( ile || sei )

  • Gurus
  • 14,264 posts
  • LocationCheshire, UK

Posted 15 November 2012 - 07:14 PM


while($item = mysql_fetch_row($package)){

$arr[$item[0]][$item[1]] = array('description' => $item[2], 'image' => $item[3]);

}


|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts
|baaSelect| generate js and php code for dynamic linked dropdowns

 


#3 chachew

chachew

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 15 November 2012 - 10:26 PM

Brilliant! Exactly what i've been banging my head against the wall to achieve




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com