在PHP中删除JSON数组元素,然后重新编码为JSON [英] deleting JSON array element in PHP, and re-encoding as JSON

查看:502
本文介绍了在PHP中删除JSON数组元素,然后重新编码为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function deleteNews($selected) {
    $file = file_get_contents('news.json', true);

    $data=json_decode($file,true);
    unset($file);

foreach($selected as $index){
 unset($data[$index]);
 }


  $result=json_encode($data);

  file_put_contents('news.json', $result);
    echo $result;
    unset($result);
    $url="./deleteNews.php";
   //redirect($url);
    }

上面的功能应该从JSON中删除一个条目,例如:

The above function is supposed to delete an entry from a JSON like :

[
     {
           "dummy":"dummy",
           "dummy1":"dumy"
      },
      {
           "dummy":"dummy1",
           "dummy1":"dummy"
      }
]

但是最后该函数在JSON中插入数字索引,这是不希望的.

But in the end the function inserts numerical indexes in the JSON, which is not desirable.

结果就像

[
    "0":
       {
          "dummy":"dummy",
          "dummy1":"dumy"
       },
     "1":
       {
           "dummy":"dummy1",
           "dummy1":"dummy"
       }
 ]

如何从中获取我的原始JSON格式?我不要那个0 1 2索引部分.

How can I get my original JSON format from this? I don't want that 0 1 2 index part.

N.B:是foreach来完成的.如果没有foreach,则将按预期方式创建JSON.

N.B: it's the foreach that does this. Without the foreach, the JSON is created as expected.

推荐答案

尝试使用array_values:

Try it with array_values:

$result = json_encode(array_values($data));

这篇关于在PHP中删除JSON数组元素,然后重新编码为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆