简体   繁体   English

在PHP中遍历三维数组

[英]looping through tridimensional arrays in php

I have an array of arrays that looks like this: 我有一个看起来像这样的数组数组:

Array
 (
[0] => Array
    (
        [id] => 39
        [nume] => Ardeleanu
        [prenume] => Bogdan
        [crm] => Array
            (
            )

    )


[1] => Array
    (
        [id] => 40
        [nume] => Avram
        [prenume] => Corina
        [crm] => Array
            (
                [2014-02-27] => 2
                [2014-02-28] => 1
            )

    )
)

Here is my code : 这是我的代码:

foreach ($newOrders as $crm) {
   foreach ($crm as $angajati) {
      foreach ($angajati['crm'] as $val) {
        echo $val;
      }
   }
}

I getting the Warning: 我得到警告:

Illegal string offset 'crm'. 字符串偏移量'crm'不合法。

What am I missing ? 我想念什么?

You're trying to loop over whole 2-nd level array, but only crm key points to array. 您试图遍历整个2级数组,但是只有crm关键点指向数组。 Thus, you need to do: 因此,您需要执行以下操作:

foreach ($newOrders as $crm) 
{
   if(isset($crm['crm']))
   {
     foreach ($crm['crm'] as $val) 
     {
          echo $val;
     }
   }
}

-if you want to get values in crm key. -如果要在crm键中获取值。 It may not exist, thus, I've added isset check. 它可能不存在,因此,我添加了isset检查。

Does it helps ? 有帮助吗?

foreach ($newOrders as $key=>$val) {
 if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){
   foreach($val["crm"] as $k=>$v){
     echo $k." = ".$v."<br />";
   }
 }
}

When we loop through a multi dimentional array its better to check if the keys are available if the corresponding values are again array and also to check if the array of values have some elements before doing loop. 当我们遍历多维数组时,最好先检查键是否可用(如果对应的值又是数组),并且还要在循环之前检查值数组是否包含某些元素。

So here first checking if "crm" is available and if the value ie again an array having some elements before doing a loop and its done by the line 因此,这里首先检查“ crm”是否可用以及值,即在执行循环之前再次检查包含某些元素的数组,并由该行完成

if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){

This is done to avoid further notice like invalid index and invalid argument supplied in foreach if the element is missing or the data array is not present. 这样做是为了避免进一步通知,例如在元素缺失或数据数组不存在的情况下,foreach中提供了无效的索引和无效的参数。

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

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