1

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?

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I think he's looking for a way to print it out, not just to store it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.