dongyan6910 2009-07-25 09:14
浏览 240
已采纳

在PHP中提取多维数组的叶节点

Suppose I have an array in PHP that looks like this

array
(
   array(0)
   (
       array(0)
       (
         .
         . 
         .
       )

       .
       .
       array(10)
       (
         ..
       )
   )

   .
   . 
   .
   array(n)
   (

     array(0)
     (
     )
   )
 )

And I need all the leaf elements of this mulit-dimensional array into a linear array, how should I go about doing this without resorting recursion, such like this?

 function getChild($element)
 {

     foreach($element as $e)
     {

       if (is_array($e)
       {
          getChild($e);
       }
     }
 }

Note: code snippet above, horribly incompleted

Update: example of array

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Seller Object
                        (
                            [credits:private] => 5000000
                            [balance:private] => 4998970
                            [queueid:private] => 0
                            [sellerid:private] => 2
                            [dateTime:private] => 2009-07-25 17:53:10
                        )

                )

        )

...snipped.

[2] => Array
    (
        [0] => Array
            (
                [0] => Seller Object
                    (
                        [credits:private] => 10000000
                        [balance:private] => 9997940
                        [queueid:private] => 135
                        [sellerid:private] => 234
                        [dateTime:private] => 2009-07-14 23:36:00
                    )

            )

    ....snipped....

    )

)

  • 写回答

6条回答 默认 最新

  • dswm97353 2009-07-25 10:27
    关注

    Actually, there is a single function that will do the trick, check the manual page at: http://php.net/manual/en/function.array-walk-recursive.php

    Quick snippet adapted from the page:

    $data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');
    
    var_dump($data);
    
    function printValue($value, $key, $userData) 
    {
        //echo "$value
    ";
        $userData[] = $value;
    }
    
    
    $result = new ArrayObject();
    array_walk_recursive($data, 'printValue', $result);
    
    var_dump($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?