【问题标题】:Removed empty array element to json_encode after将空数组元素删除到 json_encode 之后
【发布时间】:2014-03-05 11:52:21
【问题描述】:

我有一个简单的数组

$a = ['a', '', 'b','c','d'];

如果我 json_encode 我会拥有

["a","","b","c","d"]

但如果我尝试删除空值,使用 array_filter 或 array_diff

我会的

{"0":"a","2":"b","3":"c","4":"d"}

但是我不需要对数组键进行编码,我需要一个没有空元素且没有数组键的编码数组,如何解决?

PHP 沙盒示例:http://sandbox.onlinephpfunctions.com/code/91635a5df7fcd954dd64fe92089f2beadc81c3c4

【问题讨论】:

    标签: php json array-difference array-filter


    【解决方案1】:

    试试这个:

    $a = array_values(array_filter($a));
    

    这会将数组的键重置为顺序。考虑数组键是如何工作的:

    $a = ['a', 'b'];       // [0 => 'a', 1 => 'b']
    unset($a[0]);          // [1 => 'b']
    $a = array_values($a); // [0 => 'b']
    

    【讨论】:

    • 谢谢你,就像一个魅力,你先回答,所以我标记为答案
    【解决方案2】:

    这会重置数组键

    $a = ['a', '', 'b', 'c', 'd'];
    echo json_encode(array_values(array_filter($a)));
    

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 2023-03-09
      • 2013-08-06
      • 2017-02-03
      • 2016-08-26
      • 2019-10-21
      • 2018-08-06
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多