P粉0434701582023-09-04 14:57:41
You are closer than you think. Just call your function recursively and add the results to the final array.
public function flattingTree(array $tree) { $denormalizeTree = []; foreach ($tree as $node) { if (isset($node['nodes'])) { $denormalizeTree += $this->flattingTree($node['nodes']); } $denormalizeTree[$node['id']] = $node['text']; } return $denormalizeTree; }
result:
$result = $this->flattingTree($array); print_r($result); Array ( [11] => Flowchart [12] => Pseudo code [2] => Algoritma [4] => Java [8] => Yii2 Framework [9] => Laravel [5] => PHP [7] => Javascript [3] => Pemrograman [13] => Mac OS [14] => Linux [10] => Sistem Operasi )
P粉8073979732023-09-04 13:40:19
A quick solution is to use a recursive function to iterate through the array and add the required data to the final array.
The key is to have a function that accepts an "unexpanded" array and a variable to hold the data (the data will be held in the variable). The last argument will be passed by reference so that the variable itself is mutated to hold the data in it.
function extract($arr, &$saveInto) { foreach ($arr as $el) { isset($el['id'], $el['text']) && ($saveInto[$el['id']] = $el['text']); isset($el['nodes']) && extract($el['nodes'], $saveInto); // 递归调用 } }
Using the above function, you can expand the array by calling it and specifying a variable to save the result.
$unflattenedArr = [ ... ]; // 要展开的数组 $finalArr = []; // 将保存结果的数组 extract($unflattenedArr, $finalArr); // 此时 $finalArr 中保存了所需的结果。
To make things simpler, you can encapsulate the extract
function, no longer needing to prepare an empty array to save the results.
function flatten($arr) { $r = []; // 此函数准备一个空变量 extract($arr, $r); // 将其传递给“extract”函数 return $r; // 然后返回带有所需结果的变量 }
Now, the array can be expanded as follows:
$unflattenedArr = [ ... ]; // 要展开的数组 $finalArr = flatten($unflattenedArr); // 调用封装了“extract”函数的新函数 // 此时 $finalArr 中保存了所需的结果。
Hope I've helped you further.