【问题标题】:How to construct an array recursively based on each parent id如何根据每个父id递归构造一个数组
【发布时间】:2014-07-08 13:36:57
【问题描述】:

我有一个嵌套的类别列表,其中 DB 看起来像这样:

id      parent_id       title
83      81              test3
86      83              test1
87      83              test2
94      87              subtest2.1
95      87              subtest2.2
...etc...

我需要将所有子元素 id 添加到每个父 id 的 $checked_elements 数组中。

因此,如果选择了某个特定的 id,它会自动添加到 $checked_elements 的数组中。如下所示:

我被递归函数困住了,关于如何递归地添加每个父项 id 的子项?我的功能不会比第二级更深,谁能告诉我如何解决它以便检查所有子项?

private function delete( ){

    // Collect all checked elements into the array
    $checked_elements = $this->input->post('checked');

    // Recursive function to check for child elementts
    foreach( $checked_elements as $key => $value ){

        // Get records where parent_id is equal to $value (checked item's id)
        $childs = $this->categories_model->get_by(array('parent_id' => $value));

        // Add found record's id into the array 
        foreach( $childs as $child ){

            $checked_elements[] => $child->id;

        }

    }

}

【问题讨论】:

  • Creating a Multi-Dimentional from another Multi Dimensional Array 的可能重复项......同样的问题其他公式......
  • @bwoebi 感谢您的通知,但我觉得您不明白我想要什么。我希望将所有找到的元素添加到 1 级数组中,如下所示:$key => $id。重复的文章与我想要的略有不同,也许有相同的逻辑,但这就是我想要理解的,如果你能得到关于我的问题的更多信息,我会非常友好。谢谢

标签: php arrays codeigniter recursion


【解决方案1】:

您可以尝试通过引用传递累加器数组:

function collect($ids, &$items) {
    foreach($ids as $id){
        $items[] = $id;
        $childs = $this->categories_model->get_by(array('parent_id' => $id));
        collect(array_column($childs, 'id'), $items);
    }
    return $items;
}

function delete( ){
    $items = array();
    collect($this->input->post('checked'), $items);
    //... delete $items
}

在 php 5.5+ 中,您还可以以类似的方式使用生成器:

function collect($ids) {
    foreach($ids as $id) {
        yield $id;
        $childs = $this->categories_model->get_by(array('parent_id' => $id));
        foreach(collect(array_column($childs, 'id')) as $id)
            yield $id;
}


function delete( ){
    $ids = collect($this->input->post('checked'));

我假设您的树相当小,否则我会建议一种更有效的方法,例如嵌套集。

如果你的php版本不支持array_column,你可以使用this shim

【讨论】:

  • 谢谢 Georg,但您能否修改您的答案以使其适用于低于 5.5 的 PHP 版本?我的服务器是php 5.4,不支持array_column()
  • @aspirinemaga:你可以使用垫片 - 我用链接更新了帖子。
猜你喜欢
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 2013-07-10
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多