PHP:通过数组迭代?

时间:2010-06-22 12:35:48

标签: php arrays recursion multidimensional-array

  • 我想要的是一个功能 搜索我的数组,和 返回所有 孩子到特定节点。什么是 这样做最合适的方法? 在这种情况下,递归是否必要?

我之前已经构建了一些相当复杂的函数,可以通过多维数组递归或不通过递归来重复它们,但是这个问题让我完全陷入困境,我不能只是把它弄清楚。 ..

这是我的数组:

Array
(
    [1] => Array (
            [id] => 1
            [parent] => 0

        )

    [2] => Array (
            [id] => 2
            [parent] => 1
        )

    [3] => Array (
            [id] => 3
            [parent] => 2
        )   
)

非常感谢,

更新:
我想得到的输出。抱歉这个坏例子,但我会因为缺乏关于如何格式化我需要做的事情的知识而责怪它。)

function getAllChildren($id) {
    // Psuedocode
    return $array;
}

getAllChildren(1); // Outputs the following:

Array
(   
    [2] => Array (
            [id] => 2
            [parent] => 1
        )

    [3] => Array (
            [id] => 3
            [parent] => 2
        )   
)

3 个答案:

答案 0 :(得分:4)

$nodes = array( 1   => array (  'id'        => 1,
                                'parent'    => 0
                             ),
                2   => array ( 'id'         => 2,
                               'parent'     => 1
                             ),
                3   => array ( 'id'         => 3,
                               'parent'     => 2
                             )
                );


function searchItem($needle,$haystack) {
    $nodes = array();
    foreach ($haystack as $key => $item) {
        if ($item['parent'] == $needle) {
            $nodes[$key] = $item;
            $nodes = $nodes + searchItem($item['id'],$haystack);
        }
    }
    return $nodes;
}


$result = searchItem('1',$nodes);
echo '<pre>';
var_dump($result);
echo '</pre>';

searchItem()函数的非递归版本:

function searchItem($needle,$haystack) {
    $nodes = array();
    foreach ($haystack as $key => $item) {
        if (($item['parent'] == $needle) || array_key_exists($item['parent'],$nodes)) {
            $nodes[$key] = $item;
        }
    }
    return $nodes;
}

(假设父/子的排序,所以子节点不包含在数组中,除非父节点已存在)

答案 1 :(得分:1)

<?php
function searchItem($needle)
{
    foreach ($data as $key => $item)
    {
        if ($item['id'] == $needle)
        {
            return $key;
        }
    }
    return null;
}
?>

答案 2 :(得分:1)

查看PHP中的array_walk_recursive()函数:

http://www.php.net/manual/en/function.array-walk-recursive.php

相关问题