0

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

$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;
}
4

2 回答 2

0

要递归地遍历多维数组,请使用array_walk_recursive函数。

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

于 2013-03-07T14:32:14.200 回答
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
于 2013-03-07T14:33:54.163 回答