提取在PHP多维阵列的叶节点 [英] Extract leaf nodes of multi-dimensional array in PHP

查看:91
本文介绍了提取在PHP多维阵列的叶节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我有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);
       }
     }
 }

请注意:以上code片段,可怕的未完成

Note: code snippet above, horribly incompleted

更新:例如数组

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
                        )

                )

        )

...剪断。

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

    )

推荐答案

其实,有一个单一的功能,会做的伎俩,在检查手册页:<一href=\"http://php.net/manual/en/function.array-walk-recursive.php\">http://php.net/manual/en/function.array-walk-recursive.php

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

快速片段改编自页:

$data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');

var_dump($data);

function printValue($value, $key, $userData) 
{
	//echo "$value\n";
	$userData[] = $value;
}


$result = new ArrayObject();
array_walk_recursive($data, 'printValue', $result);

var_dump($result);

这篇关于提取在PHP多维阵列的叶节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆