traversing an array in php [duplicate]

≯℡__Kan透↙ 提交于 2019-12-02 10:10:42
foreach($object as $key=>$value){
    if( is_array($value) ) {
        foreach($value as $key2=>$value2) {
            //stuff happens
        }
    } else {
        //other stuff
    ]
}

You can try:

function traverse($array) {
   foreach ($array as $key => $value) {
      if (is_array($value)) {
         traverse($array);
         continue;
      }
      echo $value;
   }
}

Try:

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

Manual for foreach

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.

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;
    }
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!