简体   繁体   English

在php中遍历多维数组

[英]Looping through a multidimensional array in php

i have this multidimensional array in php and I need be able to access all the elements including the first element "Computers". 我在php中有这个多维数组,我需要能够访问所有元素,包括第一个元素“ 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 这是$ 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 但是当我记录$ 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 

where is the text "Computers", "Screens" 文本“计算机”,“屏幕”在哪里

You are adding next element to $left and $right when you use [], and its numerical. 当您使用[]及其数字时,将向$ left和$ right添加下一个元素。 Try: 尝试:

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

You need to use a foreach loop with $key variable: 您需要使用带有$key变量的foreach循环:

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. 此变量( $arrayIndex ,可以确定为任何名称),将在foreach循环中保存数组索引字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM