0

Possible Duplicate:
Loop an array of array

So I know how to traverse an array of even key => value (associative), but I have a weird array where I need to walk through it and print out values:

$object_array = array(
    'type' => 'I am type',
    array(
        'property' => 'value',
        'property_2' => 'value_2'
    )
);

What I thought I could do is:

foreach($object as $key=>$vlaue){
   //what now?
}

So as you can see I am lost, how do I walk through the next array?

0

6 Answers 6

7

You can try:

function traverse($array) {
   foreach ($array as $key => $value) {
      if (is_array($value)) {
         traverse($array);
         continue;
      }
      echo $value;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach($object as $key=>$value){
    if( is_array($value) ) {
        foreach($value as $key2=>$value2) {
            //stuff happens
        }
    } else {
        //other stuff
    ]
}

Comments

0

Try:

foreach($object_array as $value) {
  if(!is_array($value))
   echo $value;
   else {
    foreach($value as $m)
    echo $m; 
  }
 }

Manual for foreach

Comments

0

In your for loop you could do:

if(is_array($object[$key]))
    //process inner array here

It depends on how deep your arrays go, if you have arrays of arrays of arrays...and so on, a different method would be better, but if you just have one level this is a pretty simple way of doing it.

Comments

0

Well, you could do something like this:

foreach($object_array as $key=>$value)
{
    if(is_array($value) {
        foreach($value as $k=>$v) {
            echo $k." - ".$v;
        }
    } else {
        echo $key." - ".$value;
    }
}

Comments

0

An alternative with array_walk_recursive():

function mydebug($value, $key) {
    echo $key . ' => ' . $value . PHP_EOL;
}

array_walk_recursive($object_array, 'mydebug');

Handy if you doing something simple with the values (e.g. just echo ing).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.