php - 使用 PHP 从 json 文件中删除对象

标签 php json

嗯,我有一个网络项目,我必须暂时保存一些东西,我开始使用 json 文件,到目前为止我可以添加和更新。 json 文件如下所示:

[
  {
    "username": "Baldwin",
    "products": [
      {
        "id": 0,
        "amount": 10
      },
      {
        "id": 1,
        "amount": 9
      },
      {
        "id": 2,
        "amount": 9
      }
    ]
  },
  {
    "username": "Alice",
    "products": [
      {
        "id": 0,
        "amount": 11
      },
      {
        "id": 1,
        "amount": 13
      },
      {
        "id": 2,
        "amount": 6
      }
    ]
  },
  {
    "username": "Terry",
    "products": [
      {
        "id": 0,
        "amount": 12
      },
      {
        "id": 1,
        "amount": 14
      },
      {
        "id": 2,
        "amount": 5
      }
    ]
  }
]

当我想删除一个特定的数组或者当我想完全删除它时,问题就出现了,我可以做到并且工作正常,但我怀疑为什么当我删除对象时,其他字段被添加到json 文件,如 id。

当我只删除“产品”数组中的一个产品时,会发生如下情况:

[
  {
    "username": "Baldwin",
    "products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
  },
  {
    "username": "Alice",
    "products": [
      { "id": 0, "amount": 11 },
      { "id": 1, "amount": 13 },
      { "id": 2, "amount": 6 }
    ]
  },
  {
    "username": "Terry",
    "products": [
      { "id": 0, "amount": 12 },
      { "id": 1, "amount": 14 },
      { "id": 2, "amount": 5 }
    ]
  }
]

当我从 json 文件中删除完整的数组时,会发生这样的事情:

{
  "1": {
    "username": "Alice",
    "products": [
      { "id": 0, "amount": 11 },
      { "id": 1, "amount": 13 },
      { "id": 2, "amount": 6 }
    ]
  },
  "2": {
    "username": "Terry",
    "products": [
      { "id": 0, "amount": 12 },
      { "id": 1, "amount": 14 },
      { "id": 2, "amount": 5 }
    ]
  }
}

我要删除的 php 文件:

<?php 

    // load file
    $data = file_get_contents('results.json');

    // decode json to associative array
    $json_arr = json_decode($data, true);

    $flag = false;
    // We check if the user wants to delete all or just one product
    if(isset($_POST["all"])):

        $username = $_POST["username"];

        foreach ($json_arr as $key => $value):

            // find the username on the json file
            if($value["username"] == $username):

                unset($json_arr[$key]);
                break;

            endif;

        endforeach; 

    elseif(isset($_POST["one"])):

        $username = $_POST["username"];
        $id = $_POST["id"];

        foreach ($json_arr as $key => $value):

            // find the username on the json file
            if($value["username"] == $username):

                // loop products of the current username
                foreach ($json_arr[$key]["products"] as $k => $product):

                    // find the id of the product 
                    if($json_arr[$key]["products"][$k]["id"] == (int)$id):

                        // delete the product
                        unset($json_arr[$key]["products"][$k]);

                    endif;

                endforeach;

            endif;

        endforeach; 

    endif;

     // encode json and save to file
    file_put_contents('results.json', json_encode($json_arr));

    // redirect to show.php
    header("Location: show.php");
?>

我一直在研究这样的问题,但我找不到 php 的东西,我想知道如何解决这个问题或者这是否正常。

最佳答案

当您使用unset($json_arr[0])时会发生的情况是第一个元素被删除,但键没有更新。如果您在删除后检查数组,您会发现数组有两个元素,分别为 $json_arr[1]$json_arr[2]

当您对此执行 json_encode($json_arr) 时,PHP 的 JSON 解码器会查看数组,因为数组应该从第 0 个元素开始,但是该数组从 1 开始,它决定为了保留键,该数组必须转换为关联数组 - 它将整数数组键转换为 JSON 中的字符串键。

要获得简短快速的解决方案,您可以尝试:

$json_arr = array_diff($json_arr, [$key]);

您甚至可以使用array_splicearray_values - see here寻找灵感。

关于php - 使用 PHP 从 json 文件中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053996/

相关文章:

php - 为什么我的数据库表没有得到更新

json - 将 json 文件导入沙发 db-

java - 相当于java中php中的bcdiv

php - Zend中的分页不起作用

javascript - Ajax 将数组保存到全局变量中不起作用,一直未定义

php - 如何让 MySQL 查询文本分割,

arrays - 如何在shell脚本中获取JSON中向量的大小?

jquery 自动完成动态生成的文本框不起作用

c# - JObject 结构 - 如何迭代?

javascript - 从 HTTP POST 请求中检索 JSON