我有一个我想要展平的数组,但我想添加一个反斜杠和所有父键。我有一个例子,有人可以帮帮我吗?该数组可以包含更多5个级别
Cars
Mercedes
BMW
Chevrolet
Caprice
Other
Motors
Yamaha
Suzuki
Cars
Cars\Mercedes
Cars\BMW
Cars\Chevrolet
Cars\Chevrolet\Caprice
Cars\Chevrolet\Other
Motors
Motors\Yamaha
Motor\Suzuki
答案 0 :(得分:4)
我已经快速演示了你所要求的内容,但不确定你的数组与我在这里测试的数据有多相似。如果您需要更多帮助,请告诉我,这是一个有趣的问题。
<?php
$arr = array(
'val1' => 1,
'val2' => 2,
'val3' => array(
'val3.1' => 1,
'val3.2' => array(
'val3.2.1' => 1
),
'val3.3' => 3
),
'val4' => 4
);
function arrayToPath($array, $path = ''){
$paths_out = array();
foreach($array as $key => $value){
$path .= '\\' . $key;
$paths_out[] = $path;
if(true === is_array($value)){
$paths_out = array_merge($paths_out, arrayToPath($value, $path));
}
}
return $paths_out;
}
$path_outputs = arrayToPath($arr);
var_dump($path_outputs);
?>
将输出:
array(8) {
[0]=> string(5) "\val1"
[1]=> string(10) "\val1\val2"
[2]=> string(15) "\val1\val2\val3"
[3]=> string(22) "\val1\val2\val3\val3.1"
[4]=> string(29) "\val1\val2\val3\val3.1\val3.2"
[5]=> string(38) "\val1\val2\val3\val3.1\val3.2\val3.2.1"
[6]=> string(36) "\val1\val2\val3\val3.1\val3.2\val3.3"
[7]=> string(20) "\val1\val2\val3\val4"
}
答案 1 :(得分:3)
尝试使用这种简单的递归方法:
<?php
$catalog = [
'Cars' => [
'Mercedes' => [],
'BMW' => [],
'Chevrolet' => [
'Caprice',
'Other'
],
],
'Motors' => [
'Yamaha',
'Suzuki'
]
];
function flattenCatalog($input, $location='') {
$output = [];
foreach ($input as $key=>$val) {
if (is_array($val)) {
$output[] = $location.'\\'.$key;
foreach (flattenCatalog($val, $location.'\\'.$key) as $subval) {
$output[] = $subval;
}
}
else {
$output[] = $location.'\\'.$val;
}
}
return $output;
}
print_r(flattenCatalog($catalog));
输出显然是:
Array
(
[0] => \Cars
[1] => \Cars\Mercedes
[2] => \Cars\BMW
[3] => \Cars\Chevrolet
[4] => \Cars\Chevrolet\Caprice
[5] => \Cars\Chevrolet\Other
[6] => \Motors
[7] => \Motors\Yamaha
[8] => \Motors\Suzuki
)