展平多维数组

时间:2020-01-10 13:11:16

标签: php arrays

我找不到从多维数组中删除空数组的好答案。

例如,我有以下数组:

$array = [
    [
        [
            [
                'some key' => 'some value'
            ]
        ]
    ]
];

在我想要这样的东西之后:

$array = [
    'some key' => 'some value'
];

我找不到解决方案。我对此的解决方案仅在没有键值对的情况下有效。

$array = array_map('array_filter', $array);
$array = array_filter($array);

4 个答案:

答案 0 :(得分:1)

正如@ vivek_23所说,从技术上讲,它不是空的,但这是一种解决方法:

<?php

$array = [
    [
        [
            [
                'some key' => 'some value',
            ]
        ]
    ]
];

function recursiveSanitizer($input) {
    foreach ($input as $layer) {
        if (isset($layer[0]) && !empty($layer[0])) {
            return recursiveSanitizer($layer);
        } else {
            return $layer;
        }
    }
}

var_dump(recursiveSanitizer($array));

答案 1 :(得分:1)

您可以通过递归地遍历数组直到array_key不是0来实现此目的:

while (is_array($array) && count($array) == 1 && array_keys($array)[0] === 0)
    $array = $array[0];

输出:

var_dump($array);

array(1) {
  ["some key"]=>
  string(10) "some value"
}

这是如何工作的?

而:

  • $array是一个数组
  • 数组中的项目数为1
  • 第一个数组键是0

while循环会将$array设置为键为0的项目。

对于要查找的阵列,这不是正确的。

答案 2 :(得分:0)

您对递归有一个正确的想法。您可以做的是检查当前元素是否为数组,如果是,则再次使用该数组调用该函数,直到找到不是数组的元素。您可以将该元素返回到另一个数组中,该数组将递归地填充非空值。

我创建了这个简单的函数,适用于您的示例。如果数组中有多个像这样的元素,它将无法正常工作。

<?php
// example code

$array = [
    [
        [
            [
                'some key' => 'some value'
            ]
        ]
    ]
];

function recursivelyRemoveTechnicallyNotEmptyArray($array) {
    // this will keep the value that are not emtpy
    $arrayWithValue = [];
    // in our case. the first case can be 0 or "some key". We need to take care of both cases.
    $firstkey = array_keys($array)[0];
    // if the first element is an array, we do a recursive call with that element
    if(is_array($array[$firstkey])) {
        // we append the result of the recursive call to the current return value.
        $arrayWithValue = array_merge($arrayWithValue, recursivelyRemoveTechnicallyNotEmptyArray($array[$firstkey]));
    } else {
        // it is not an array, we push it into what we are going to return
        $arrayWithValue[] = $array[$firstkey];
    }
    return $arrayWithValue;
}

var_dump(recursivelyRemoveTechnicallyNotEmptyArray($array));

我也created a playground供您测试。

答案 3 :(得分:0)

您可以使用array_walk_recursive轻松访问数组“叶”:

<?php
$array = [
    [
        [
            [
                'some key' => 'some value'
            ]
        ]
    ]
];

array_walk_recursive($array, function($v, $k) use (&$result) {
    $result[$k] = $v;
});

var_export($result);

输出:

array (
  'some key' => 'some value',
)