我正在尝试将子数组数据移动到父级,如果它只包含一个元素且父数组键是数字。我不想完全压扁它。我想保留数组的结构。除了顶部数组之外,所有子数组都不应该有数字键。
我的输入数据:
[8] => Array
(
[any] => Array
(
[0] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test1
)
[1] => Array
(
[0] => Array
(
[any] => Array
(
[0] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test2
)
[1] => stdClass Object
(
[f] => test3
)
)
)
)
)
)
)
)
)
)
)
我想要的输出:
[8] => Array
(
[any] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test1
)
[any] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test2
)
[1] => stdClass Object
(
[f] => test3
)
)
)
)
)
)
)
我正在尝试使用多维数组。 我尝试了以下功能。
public function flattenKeyZero(&$arr) {
foreach ($arr as $k => &$v) {
if (is_array($v)) {
if ( (count($v) == 1 && is_numeric(key($v)) ) ) { // Check count and key if numeric; Check count and parent array contains only all or any
$arr[$k] = reset($v); // Return child array by reset
}else {
$this->flattenKeyZero($v);
}
}
}
}
do {
$temp = $arr;
$this->flattenKeyZero($arr);
}while ($temp != $arr ) ;
我得到了以下输出。一切看起来不错,除了我无法修改它以满足条件“ 没有子数组应该有数字键“
[8] => Array
(
[any] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test
)
[1] => Array
(
[any] => Array
(
[all] => Array
(
[0] => stdClass Object
(
[f] => test
)
[1] => stdClass Object
(
[f] => test
)
)
)
)
)
)
)
)
我也尝试过添加额外的elseif条件,但它似乎不起作用..
elseif((is_numeric($k) && (key($v) == 'all' || key($v) == 'any') && count($v) == 1 )){ // if all or any are under numeric index array , remove numeric index array and move a level up
$arr[key($v)] = reset($v);
}
答案 0 :(得分:0)
一种方法是在检查计数后使用reset()
,如果是is_numeric
foreach ($arr as $key => $value) {
if (count($value) == 1 && is_numeric(key($value))) { // Check count and key if numeric
$arr[$key] = reset($value); // Return child array by reset
}
}
print_r($arr);