douna2014
douna2014
2012-11-15 21:47
浏览 13
已采纳

遍历php中的数组[重复]

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • douci1615
    douci1615 2012-11-15 21:53
    已采纳
    foreach($object as $key=>$value){
        if( is_array($value) ) {
            foreach($value as $key2=>$value2) {
                //stuff happens
            }
        } else {
            //other stuff
        ]
    }
    
    点赞 评论
  • dprfe04886
    dprfe04886 2012-11-15 21:50

    Try:

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

    Manual for foreach

    点赞 评论
  • dongliang1865
    dongliang1865 2012-11-15 21:51

    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.

    点赞 评论
  • doulan1073
    doulan1073 2012-11-15 21:51

    You can try:

    function traverse($array) {
       foreach ($array as $key => $value) {
          if (is_array($value)) {
             traverse($array);
             continue;
          }
          echo $value;
       }
    }
    
    点赞 评论
  • douqu8828
    douqu8828 2012-11-15 21:53

    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;
        }
    }
    
    点赞 评论
  • dsce23640
    dsce23640 2012-11-15 21:54

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

    点赞 评论

相关推荐