skjalal
skjalal

Reputation: 19

looping multidimensional arrays with associative and index array

$cars7=array( array( array('a1','b1','c1'), array('a2','b2','c2'), array('q'=>'a','b'=>'b','c'=>'c') )
);

I tried the for loop with how we write the code for index array same i tried for mixed multidimensional array by showing error could not convert string to array.

----php multidimensional for loop.

$cars7=array(
          array(
          array('a1','b1','c1'),
          array('a2','b2','c2'),
          array('q'=>'a','b'=>'b','c'=>'c')
 )        
);



 for($i=0;$i<=count($cars7)-1;$i++) 
             {
             for($j=0;$j<=count($cars7[0])-1;$j++) 
            {
             echo $cars7[$i][$j].'<br><br>';

        }

    }

I don't know how to loop multidimensional array which contains index array and associative array.

I need help from expertise, Please correct the above code.

Upvotes: 0

Views: 60

Answers (2)

The fourth bird
The fourth bird

Reputation: 163457

Another option to get all the values is to use array_walk_recursive

$cars7 = array(
    array(
        array('a1', 'b1', 'c1'),
        array('a2', 'b2', 'c2'),
        array('q' => 'a', 'b' => 'b', 'c' => 'c')
    )
);

array_walk_recursive ($cars7, function($value){
    echo $value . '<br>';
});

Result

a1
b1
c1
a2
b2
c2
a
b
c

Php demo

Upvotes: 0

FoulFoot
FoulFoot

Reputation: 654

This might help:

$cars[0] is:

array(
      array('a1','b1','c1'),
      array('a2','b2','c2'),
      array('q'=>'a','b'=>'b','c'=>'c')
)   

$cars[0][0] is:

array('a1','b1','c1')

$cars[0][0][0] is:

a1

You've got the right idea, you just need to start your loop a little "deeper". And to loop through the arrays, use foreach:

foreach ( $cars[0] as $test )
{
   foreach ( $test as $entry )
   {
      echo $entry.'<br><br>';
   }
}

Upvotes: 1

Related Questions