【问题标题】:Converting sequential array to json after deleting some elements删除一些元素后将顺序数组转换为 json
【发布时间】:2018-01-31 11:29:58
【问题描述】:

所以我有一个 json 字符串和一个像这样的数组:

$json_str = '{"key1":["val11", "val12", "val13"], "key2":"val2"}';
$delete_keys = array("val12");

我想从 json_str['key1'] 中删除 delete_keys 中存在的值。所以我做了以下事情:

$json_arr = json_decode($json_str, true);
$key1 = $json_arr['key1'];
foreach ($delete_keys as $key) {
    $index = array_search($key, $key1);
    if (isset($index))
        unset($key1[$index]);
    unset($index);
}
$json_arr['key1'] = $key1;
$json_str = json_encode($json_arr);
print $json_str;

现在我对 json_str 的预期结果是这样的

{"key1":["val11", "val13"], "key2":"val2"}

但是我得到了这个

{"key1":{"0":"val11", "2":"val13"}, "key2":"val2"}

如果我删除最后一个键,它会按预期工作。有人可以告诉我如何将前者作为 json 字符串而不是后者。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您应该使用 array_values() 重新索引数组。

    如果数组中的键不是连续的,则它是一个关联数组。

    【讨论】:

      【解决方案2】:

      在 json_encode 的 PHP 文档中有一个这种现象的例子,标记为“Sequential array with one key unset”:http://php.net/manual/en/function.json-encode.php

      转载于此:

      $sequential = array("foo", "bar", "baz", "blong");
      // ...
      unset($sequential[1]);
      var_dump(
       $sequential,
       json_encode($sequential)
      );
      // Outputs: string(33) "{"0":"foo","2":"baz","3":"blong"}"
      

      为了使键保持顺序,您可以使用array_values 重新编号:

      $sequential = array("foo", "bar", "baz", "blong");
      // ...
      unset($sequential[1]);
      $sequential = array_values( $sequential );
      var_dump(
       $sequential,
       json_encode($sequential)
      );
      // Outputs: string(21) "["foo","baz","blong"]"
      

      【讨论】:

        猜你喜欢
        • 2023-01-10
        • 2019-12-10
        • 2014-10-30
        • 1970-01-01
        • 2016-05-27
        • 2019-11-02
        • 1970-01-01
        • 2019-05-17
        • 2018-06-25
        相关资源
        最近更新 更多