【问题标题】:clear empty spaces array [duplicate]清除空格数组[重复]
【发布时间】:2015-12-01 18:23:18
【问题描述】:

我有这个数组,我想摆脱那些没有价值的索引,例如在 index[0] 中我想摆脱 [0] 和 [4] 所以我会有一个 3 值数组等等...

Array
(
    [0] => Array
        (
            [0] => 
            [1] => 
            [2] => 7
            [3] => 
            [4] => 8
            [5] => 
        )

    [1] => Array
        (
            [0] => 
            [1] => 
            [2] => 9
            [3] => 10
            [4] => 
        )

    [2] => Array
        (
            [0] => 
            [1] => 11
            [2] => 12
            [3] => 
        )

)

【问题讨论】:

  • 可能是array_filter?
  • 另外,您是要保留密钥还是转移它们?也就是说element[0][1]运行后应该是1还是2?

标签: php matrix web


【解决方案1】:

这是 array_filter 的一个很好的用例。检查 !empty() 允许您删除空字符串和空值。

$filter_func = function($input) {
    $output = [];
    foreach ($input as $set) {
        $output[] = array_values(
            array_filter($set, function($element) {
                return !empty($element);
            })
        );
    }
    return $output;
}

【讨论】:

  • 它有效,但我如何将内部值设置为 [0] 或 [1] 而不是前一个数组的值?数组 ( [0] => 数组 ( [2] => 7 [4] => 8 ) [1] => 数组 ( [2] => 9 [3] => 10 ) [2] => 数组 ( [ 1] => 11 [2] => 12))
  • 我刚刚更新了我的解决方案。您将使用 array_values 包装 array_filter 调用。
  • 非常感谢!它确实奏效了!
  • 这是在我的数组中删除 0 有没有办法避免这种情况? [0] => 数组([0] => 0 [1] => 0 [2] => 7 [3] => 0 [4] => 8 [5] => 0)@curtis1000
  • 在不知道您想要接受的可能性范围的情况下,我很难知道最好的过滤器是什么。如果您一直在处理整数,可以将“!empty”替换为“is_int”以仅接受整数(包括零)。
【解决方案2】:

你可以使用array_filter()

$my_array = array_filter($my_array);

如果之后需要“重新索引”,可以运行$my_array = array_values($my_array)

例子:

$a   = array();
$a[] = '';
$a[] = 1;
$a[] = null;
$a[] = 2;
$a[] = 3;

$a = array_filter($a);
print_r($a);

输出:

Array
(
    [1] => 1
    [3] => 2
    [4] => 3
)

【讨论】:

  • 我试过这个,但它对我不起作用
  • 哦。很好 array_filter 工作,但我没有意识到你正在运行一个多维数组,因为除非你手动执行它们,否则它不会在更深的数组级别中工作。
【解决方案3】:
foreach ($array as $key=>$value) {
  if ($value == '') { unset($array[$key]); }
}

应该可以的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2017-10-04
    • 1970-01-01
    • 2013-02-12
    • 2012-09-28
    • 2021-02-02
    • 1970-01-01
    相关资源
    最近更新 更多