如何在php中限制数组深度

时间:2016-10-08 08:18:50

标签: php arrays multidimensional-array

我希望在多维数组中达到10级。

这是我的代码,我从中获得无限深度,但我想将其限制为10级。

function tree($parent){
global $db;
$sql = "SELECT * FROM clients WHERE parent_id = $parent ";


$users=$db->query($sql);

$return = array();

while($parent = $users->fetchObject()) {

  $return[$parent->client_id] = $parent;


  if(have_data($parent->client_id)){

    $return[$parent->client_id]->subs = tree($parent->client_id);
  }
}

return $return;
}

的print_r(树(1,0));

输出是:

  Array
    (
    [2] => stdClass Object
    (
        [client_id] => 2
        [parent_id] => 1
        [client_name] => TEST
        [subs] => Array
            (
                [4] => stdClass Object
                    (
                        [client_id] => 4
                        [parent_id] => 2
                        [client_name] => TEST
                        [subs] => Array
                            (
                                [5] => stdClass Object
                                    (
                                        [client_id] => 5
                                        [parent_id] => 4
                                        [client_name] => ADAm
                                    )

                            )

                    )

                [6] => stdClass Object
                    (
                        [client_id] => 6
                        [parent_id] => 2
                        [client_name] => RAS
                        [subs] => Array
                            (
                                [7] => stdClass Object
                                    (
                                        [client_id] => 7
                                        [parent_id] => 6
                                        [client_name] => RAStest
                                    )

                            )

                    )

            )

    )

[3] => stdClass Object
    (
        [client_id] => 3
        [parent_id] => 1
        [client_name] => ABC
    )

  )

如何将儿童等级限制在10岁,希望得到专家老板的回应。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用RecursiveIteratorIterator API并使用setMaxDepth()功能,并可以使用此功能获取maxDepth getMaxDepth()

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));