tags:

views:

1295

answers:

2

I would like to ask how to print out this array with organize way

This is my array

> Array (
>     [item1 under Category_1] => Category_1
>     [item2 under Category_1] => Category_1
>     [item3 under Category_2] => Category_2
>     [item4 under Category_3] => Category_3
>     [item5 under Category_3] => Category_3
>     [item6 under Category_3] => Category_3
>     [item7 under Category_3] => Category_3
>     [item8 under Category_3] => Category_3 )

The output should like this:

Category_1
  item1
  item2
Category_2
  item3
Category_3
  item4
  item5
  item6
  item7
  item8

Is there any way I can do this? or my logic way to arrange my array is wrong?

My database table record is like this

category item
   1       1
   1       2
   2       3
   3       4
   3       5
   3       6
   3       7
   3       8

Anyone can help?

+1  A: 

first the query

$myarray = array();
$result = mysql_query("SELECT category , item FROM mytable order by category , item ");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

$myarray[$row['category'] ][]  = $row['item'];

}

now u get a 2 dimension array

now run on this array in 2 loop (foreach or for) and print the key of the entery and after that the items in this entery

foreach ($array as $key => $val) {
    print "Key $key\n";
    for($i=0;$i<count($val);$i++)
       print "val $val[$i]\n";


}

this is example you can improve it ; i hope the idea is clear

Haim Evgi
I think he's looking for a way to print it out, not just to store it.
musicfreak
+2  A: 

You probably need to adjust layout and line breaks, but I think you get the idea:

asort($your_array);
foreach($your_array as $key => $value){
  if($key_temp != $key){
    echo $key."\r\n";
  }  
  echo " ".$value."\r\n";  
  $key_temp = $key;
}
merkuro