LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Can't use my PHP array. (https://www.linuxquestions.org/questions/programming-9/cant-use-my-php-array-457134/)

rblampain 06-22-2006 12:14 AM

Can't use my PHP array.
 
I have a test array that displays as it was intended when using 'print_r()' but any 'foreach' or nested 'foreach' I use prints repeatedly from element 0 as follows:
0,0,1,0,1,2,0,1,2,3 etc.

Here is the result of 'print_r()':
Array ( [Aeroplane.] => Array ( [0] => .Ac8a2c300 ) [Air.] => Array ( [0] => .A113abc00 ) [Bus.] => Array ( [0] => .A63a3c300 ) [Car.] => Array ( [0] => .A52a3c300 [1] => .Aab757300 ) [Cargo ship.] => Array ( [0] => .Af8a3c300 ) [Cruise ship.] => Array ( [0] => .A0ba4c300 ) [Ferry.] => Array ( [0] => .A26a4c300 ) [Motor bike.] => Array ( [0] => .Abea3c300 ) [Push bike.] => Array ( [0] => .Adda3c300 ) [Rail.] => Array ( [0] => .A91a2c300 ) )

Each element has a name and a number of values, multiple values have to be sorted in reverse order, for example:
[Car.] => Array ( [0] => .A52a3c300 [1] => .Aab757300 )
[0] and [1] have to be sorted in this example.

Can anyone suggest how to access elements of this array and how to sort multiple values within each key?

The purpose is to present checkboxes in a form to the user with values checked when there is only 1 value for a key but ask wich one to select when there are multiple values. Any hint on this is also most welcome.

Thank you for your help.

cdhgee 06-22-2006 02:49 AM

Something like:

Code:

<?php

foreach($myarray as $k=>$v)
{
        if(is_array($v)
        {
                //child is an array, so sort and print multiple values
               
                //reverse sort the child values based on the key
                $newChildArray = krsort($v);
               
                foreach($newChildArray as $val)
                {
                        echo "<input type=\"radio\" name=\"$k\" value=\"$vals\"/>$val<br />";
                }
        }
        else
        {
                //child is not array, just print it
                echo "<input type=\"radio\" name=\"$k\" value=\"$v\"/>$v<br />";
        }
}
?>


rblampain 06-22-2006 08:52 AM

Thank you for your answer. It works well. I had an error in the script that produced the odd printing I mentioned in the first few lines.

koobi 06-22-2006 10:08 AM

if i read your post properly, you want to sort a multidimensional array, right?
In that case, you could use array_multisort()

cdhgee's method would work fine as well, the link I posted above is just another way to do it :)

rblampain 06-23-2006 07:19 AM

Thank you koobi, I'll remember that.


All times are GMT -5. The time now is 04:08 AM.