【问题标题】:Create parent-child array structure based on value comparison基于值比较创建父子数组结构
【发布时间】:2014-11-03 11:28:09
【问题描述】:

我正在尝试根据每个条目的值创建一个数组中的数组结构,但我真的不知道应该如何处理。

我希望来自 SO 的人可以帮助我有效地实现它。

到目前为止我尝试过的事情:设置父母并附加孩子,然后为每个孩子做同样的事情。

输入:

array(
  array('value' => 0),
  array('value' => 4),
  array('value' => 4),
  array('value' => 8),
  array('value' => 0),
  array('value' => 4)
)

想要的输出

array(
  array('value' => 0
      'children' => array(
          array('value' => 4),
          array('value' => 4
              'children' => array(
                   array('value' => 8)
              )
          )
      )
  ),
  array('value' => 0
      'children' => array(
          array('value' => 4)
      )
  )
)

我会很感激任何想法。我正在考虑一种递归方法来实现这一点,但是我不知道如何正确地做到这一点。

非常感谢您!

【问题讨论】:

    标签: php arrays recursion parent-child recursive-datastructures


    【解决方案1】:
    function doit(&$a , &$i)
    {
        $myval = $a[$i++]['value'];
        $chld = array();
        while( isset($a[$i]) && $a[$i]['value']>$myval )
        {
            $chld[]=doit($a ,$i);
        }
        if(count($chld)>0)
            return array('value'=>$myval,'children'=>$chld);
        else
            return array('value'=>$myval);
    }
    
    $a = array(
      array('value' => 0),
      array('value' => 4),
      array('value' => 4),
      array('value' => 8),
      array('value' => 0),
      array('value' => 4)
    );
    
    $i=0;
    $result = array();
    while(isset($a[$i]))
        $result[] = doit($a,$i);
    print_r($result);
    

    请注意,指针 $i 作为引用传递,这意味着它在所有递归调用中都是同一个变量,始终指向下一个未处理的记录。

    doit() 函数的一次运行将处理它的一个值,然后(只要存在子候选)将为其每个子递归调用自身。

    【讨论】:

    • 完美!正是我想要的。我真的很喜欢它通过使用指针提供的效率。非常感谢大卫!
    猜你喜欢
    • 2019-05-21
    • 2023-01-17
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    相关资源
    最近更新 更多