我试图将子数组数据移动到父数组,如果它只包含一个元素并且父数组键是数字。我不想完全压平它。我想保留数组的结构。除了顶部的一个之外,所有子数组都不应该有数字键。
我的输入数据:
[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);
}
一种方法是reset()
在检查计数和 if 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句