怎么做递归?

时间:2013-03-07 14:27:18

标签: php arrays recursion multidimensional-array

如何通过递归将一个数组转换为另一个数组?此示例仅适用于第二级。

$array2 = array();
foreach ($array as $levelKey => $level) {
  foreach ($level as $itemKey => $item) {
    if (isset($array[$levelKey + 1])) {
      $array2[$item['data']['id']] = $item;
      $children = $this->searchChildren($item['data']['id'], $array[$levelKey + 1]);
      $array += $children;
    }               
  }
}

function searchChildren($parent_id, $level)
{
  $_children = array();
  foreach ($level as $key => $item) {
    if ($item['data']['parent_id'] === $parent_id) {
      $_children[$key] = $item;
    }
  }
  return $_children;
}

2 个答案:

答案 0 :(得分:0)

以递归方式移动多维数组,使用 array_walk_recursive 函数。

可以在此处找到文档:http://www.php.net/manual/en/function.array-walk-recursive.php

答案 1 :(得分:0)

这是一个用于递归的简单示例。此函数递归打印数组中所有项的连接键和值

function printArrayWithKeys(array $input, $prefix = null) {
    foreach ($input as $key=>$value) {
        $concatenatedKey = $prefix . '.' . $key;
        if (is_array($value)) {
            printArrayWithKeys($value, $concatenatedKey);
        } else {
            print $concatenatedKey . ': ' . $value . "\n";
        }
    }
}

此函数的关键是在遇到另一个数组时调用自身(因此继续遍历数组的所有级别)

您可以使用以下输入调用它:

array(
    array(
        array( 'Hello', 'Goodbye' ),
        array( 'Again' )
    ),
    'And Again'
)

它会打印的地方:

0.0.0: Hello
0.0.1: Goodbye
0.1.0: Again
1: And Again