no_freedom
no_freedom

Reputation: 1961

How to traverse the variable depth items of a multidimensional array

I'm trying to print array. All code working fine, but at last I'm getting `ArrayArray'.

Here is my array

Array
(
[Post1] => Array
    (
        [id] => 1
        [title] => hi
    )
[Post2] => Array
    (
        [0] => Array
            (
                [id] => 1
            )
    )
[Post3] => Array
    (
        [0] => Array
            (
                [id] => 1
            )
    )
 )

Here is my PHP Code

foreach($post as $key => $value) {
 foreach($value as $print => $key) {
     echo "<br>".$key;
   }
}

here is output

ID
Array
Array

Upvotes: 3

Views: 114

Answers (4)

Rob
Rob

Reputation: 59

I think the trouble for you is that you have $key in the outer loop and $key in the inner loop so its really confusing which $key you are talking about for starters.

You just want the stuff printed out to debug?

echo "<pre>" . print_r( $post , true ) . "</pre>\n";

Upvotes: 0

Chris Laarman
Chris Laarman

Reputation: 1589

you are trying to print an array, resulting in Array. If you want to print an array use print_r

Upvotes: 0

alex
alex

Reputation: 490173

The to string method of an array is to return "Array".

It sounds like you want to view the array for debugging purposes. var_dump() is your friend :)

Upvotes: 0

Niklas
Niklas

Reputation: 30002

Try this:

foreach($post as $key => $value) {
 foreach($value as $print => $key) {
     if (is_array($key)){
         foreach($key as $print2 => $key2) {
          echo "<br>".$key2;
          }

     }else{
     echo "<br>".$key;
     }
   }
}

Upvotes: 3

Related Questions