Php 将子数组移动到父数组
我有一个php数组,如:-Php 将子数组移动到父数组,php,Php,我有一个php数组,如:- Array ( [colors] => Array ( [0] => white [1] => Yellow [2] => Black [3] => white [4] => Array ( [0] => white [1] => Bla
Array
(
[colors] => Array
(
[0] => white
[1] => Yellow
[2] => Black
[3] => white
[4] => Array
(
[0] => white
[1] => Black
)
[5] => Array
(
[0] => white
[1] => Black
)
[6] => white
[7] => red
)
)
现在我希望输出如下:
Array
(
[colors] => Array
(
[0] => white
[1] => Yellow
[2] => Black
[3] => white
[4] => white
[5] => Black
[6] => white
[7] => Black
[8] => white
[9] => red
)
)
表示若数组元素具有数组值,则将其移动到父元素。我不想要子层。请建议如何实现请检查此项
foreach($myarray as $array){
foreach($array as $val){
$array_1[] = $val;
}
}
您可以像这样使用
array\u splice()
:
for ($i=0; $i<count($arr['colors']); $i++) {
if (is_array($arr['colors'][$i])) {
array_splice($arr['colors'], $i, 1, $arr['colors'][$i]);
}
}
对于($i=0;$i这里有一种方法
$someArray = ['YOUR_ARRAY_HERE'];
$newArray = [];
foreach ($someArray as $value) {
if(is_array($value)) {
foreach ($value as $innerValue) {
array_push($newArray, $innerValue);
}
continue;
}
array_push($newArray, $value);
}
print_r($newArray);
尝试这一最佳解决方案
$new_array['colors'] = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$list = iterator_to_array($it,false);
$new_array['colors'] = $list;
print_r($new_array);
AnkitaAgrawal检查答案,并将一个对您正确的答案标记为已接受答案。如果其他答案有用,您也可以将其标记为已接受答案。感谢没有回应的人此答案应获得批准谢谢老兄
$new_array['colors'] = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$list = iterator_to_array($it,false);
$new_array['colors'] = $list;
print_r($new_array);