我被困了,....
我有一个这样的数组:
$myArray['red'][0] = "valueRed0";
$myArray['red'][1] = "valueRed1";
$myArray['blue'][0] = "valueBlue0";
$myArray['blue'][1] = "valueBlue1";
$myArray['green'][0] = "valueGreen0";
$myArray['green'][1] = "valueGreen1";
$myArray['green'][top][0] = "valueGreenTop0";
$myArray['green'][top][1] = "valueGreenTop1";
$myArray['green'][bottom][0] = "valueGreenBottom0";
$myArray['green'][bottom][1] = "valueGreenBottom1";
作为我需要的输出:
array(
'red/valueRed0',
'red/valueRed1',
'blue/valueBlue0',
'blue/valueBlue1',
'green/valueGreen0',
'green/valueGreen1',
'green/top/valueGreenTop0',
'green/top/valueGreenTop1',
'green/bottom/valueGreenBottom0',
'green/bottom/valueGreenButtom1'
)
所以这意味着:如果键是一个字符串,它必须是文件夹。如果键是整数,则该值必须是新值。
重要的是递归到不同大小的数组。
任何人都可以帮助我,我无法解决这个递归的事情......?
答案 0 :(得分:1)
这是一个如何完成的例子
<?php
$myArray['red'][0] = "valueRed0";
$myArray['red'][1] = "valueRed1";
$myArray['blue'][0] = "valueBlue0";
$myArray['blue'][1] = "valueBlue1";
$myArray['green'][0] = "valueGreen0";
$myArray['green'][1] = "valueGreen1";
$myArray['green']['top'][0] = "valueGreenTop0";
$myArray['green']['top'][1] = "valueGreenTop1";
$myArray['green']['bottom'][0] = "valueGreenBottom0";
$myArray['green']['bottom'][1] = "valueGreenBottom1";
print_r(flatten($myArray));
function flatten($data,$keys=array()){
$out=array();
foreach($data as $key=>$val){
if(!is_array($val)){
$out[] = implode("/",$keys)."/".$val;
}else{
$out = array_merge($out,flatten($val,array_merge($keys,array($key))));
}
}
return $out;
}
输出:
Array
(
[0] => red/valueRed0
[1] => red/valueRed1
[2] => blue/valueBlue0
[3] => blue/valueBlue1
[4] => green/valueGreen0
[5] => green/valueGreen1
[6] => green/top/valueGreenTop0
[7] => green/top/valueGreenTop1
[8] => green/bottom/valueGreenBottom0
[9] => green/bottom/valueGreenBottom1
)