你好,我需要将多维数组的结构从包含子级数据的父级更改为包含父级信息的子级
$tab = [
'movies' => [
'action',
'drama',
'comedy' => [
'romance' => ['90th'],
'boring'
]
],
'colors' => [
'red'=>'light',
'green'=> [
'dark',
'light'
],
'oragne'
]
];
转移到
$tab = [
'90th' => [
'romance' => [
'comedy' => 'movies'
]
],
'boring' => [
'comedy' => 'movies'
],
'comedy' => 'movies',
'drama' => 'movies',
'action' => 'movies',
'light' => [
'red',
'green' => 'colors'
],
'dark' => [
'green' => 'colors'
],
'oragne' => 'colors',
'green' => 'colors',
'red'
];
我知道为了获得树叶,我可以使用
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($tab), RecursiveIteratorIterator::LEAVES_ONLY) as $key => $value) {
$result[$value] = $key;
}
但它并没有像我预期的那样起作用。
这是一个非常片面的答案,所以不要抱太大希望。它也许可以扩展以解决您的问题。
要使其工作,首先需要'red'=>'light'
到'red'=>['light'}
(因此看起来像'romance' => ['90th']
(。然后它会给你一系列的平面数组,而不是你想要的深度。此外,它的排序也不像你想要的输出。
function insideOut($array, $trail) {
foreach($array as $key => $value) {
$new_trail = $trail;
if(is_array($value)) {
$new_trail[] = $key;
insideOut($array[$key], $new_trail);
}
else {
$new_trail[] = $value;
print_r($new_trail);
}
}
}
insideOut($tab, array());
这会产生以下输出:
Array
(
[0] => movies
[1] => action
)
Array
(
[0] => movies
[1] => drama
)
Array
(
[0] => movies
[1] => comedy
[2] => romance
[3] => 90th
)
Array
(
[0] => movies
[1] => comedy
[2] => boring
)
Array
(
[0] => colors
[1] => red
[2] => light
)
Array
(
[0] => colors
[1] => green
[2] => dark
)
Array
(
[0] => colors
[1] => green
[2] => light
)
Array
(
[0] => colors
[1] => oragne
)
如果你可以用赋予线索"深度"的东西来代替print_r($new_trail);
,然后保存它,问题就会得到解决。
我知道,我知道,答案不多,我也不希望得到绿色支票。但我认为,把我(很小的(进步张贴在这里总比把它扔掉要好。