ardb
ardb

Reputation: 6445

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'.

What am I missing ?

Upvotes: 1

Views: 101

Answers (2)

Alma Do
Alma Do

Reputation: 37365

You're trying to loop over whole 2-nd level array, but only crm key points to array. 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. It may not exist, thus, I've added isset check.

Upvotes: 2

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

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 i.e. again an array having some elements before doing a loop and its done by the line

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.

Upvotes: 2

Related Questions