donglu3243 2018-01-31 11:29
浏览 53
已采纳

删除一些元素后,将顺序数组转换为json

So I've a json string and an array like so :

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

I want to delete the values present in delete_keys from json_str['key1']. So I did the following:

$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;

Now the result I expected for json_str is this

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

But instead I get this

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

It works as I expected if I delete the last key though. Can someone please tell me how to get the former as the json string instead of the latter.

  • 写回答

2条回答 默认 最新

  • doumi7854 2018-01-31 11:34
    关注

    You should reindex array with array_values().

    If keys in the array are not sequential it is an associative array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算