通过php中的多维数组循环

时间:2010-09-06 21:40:50

标签: php arrays multidimensional-array

我在php中有这个多维数组,我需要能够访问所有元素,包括第一个元素“Computers”。我需要将此数组转换为两个数组,并使用此循环

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

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

这是$ 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 ( .....

但是当我记录$ left或$ 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 

文本“Computers”,“Screens”

在哪里

2 个答案:

答案 0 :(得分:3)

当你使用[]及其数字时,你正在向$ left和$ right添加下一个元素。 尝试:

foreach ($all_products as $key=>$product) {
if ($i++ % 2 == 0) {
        $left[$key][]  = $product;
    } else {
        $right[$key][] = $product;
    }
}

答案 1 :(得分:2)

您需要使用foreach循环$key变量:

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

这个变量($arrayIndex,可以肯定地命名),将在foreach循环中保存数组索引字符串。