views:

50

answers:

2

i have this multidimensional array in php and I need be able to access all the elements including the first element "Computers". I need to turn this array into two arrays and i used this loop

    $i = 0;
$left = array();
$right = array();
    foreach ($all_products as $product) {
    if ($i++ % 2 == 0) {

        $left[]  = $product;
    } else {
        $right[] = $product;
    }
}

Here is the structure of $all_products

Array ( 
  [Computers] => Array ( 
    [macbook] => Array ( [price] => 575 
                           [quantity] => 3               
                           [image] => T-SMALL-blue.png 
                           [descr] => osx
                          )
    [windows] => Array ( [price] => 285 
                         [quantity] => 1 
                         [image] => TU220-blue.png 
                         [descr] => something windows )  
                        ) 
 [Screens] => Array ( 
    [FIREBOX S5510 15", SPKRS ] => Array ( [price] => 489 
                                           [quantity] => 3 
                                           [image] => [descr] => SPKRS 
                           ) 
                        ) 
 [Software] => Array ( .....

but when i logger $left or $right

[0] => Array ( 
  [macbook] => Array ( 
     [price] => 575 
     [quantity] => 3 
     [image] => TOWER-PC-LENOVO-SMALL-blue.png 
     [descr] => osx
             ) 
  [windows] => Array ( 
     [price] => 575 
     [quantity] => 3 
     [image] => TOWER-PC-LENOVO-SMALL-blue.png 
     [descr] => something windows
) 
[1] => Array 

where is the text "Computers", "Screens"

+2  A: 

You need to use a foreach loop with $key variable:

foreach ($all_products as $arrayIndex=>$product) {

this variable ($arrayIndex, can be named anything for sure), will hold the array indexes strings inside the foreach loop.

aularon
+3  A: 

You are adding next element to $left and $right when you use [], and its numerical. Try:

foreach ($all_products as $key=>$product) {
if ($i++ % 2 == 0) {
        $left[$key][]  = $product;
    } else {
        $right[$key][] = $product;
    }
}
cichy
how do i access the string "Computer", I tried left[0] but nothing. I know i can do left["Computers"] but i dont have that value in till i pull it out
Matt
echo key($left)
cichy
yes that works but when i loop through <?php foreach ($left as $left_product): ?> <?php print key($left_product); ?> and there is 3 elements in the array all three print "Computers" strange ...any ideas
Matt
try foreach($left as $key=>$left_product) print($key), because key() has internal pointer which needs to be moved while looping. So you would have to use next() etc. (more in manual ;P )
cichy