【问题标题】:Delete from json using php使用 php 从 json 中删除
【发布时间】:2011-10-26 01:49:00
【问题描述】:

我当前的 json 代码:

{"Results":[{"username":"test","password":"test"},{"username":"test","password":"test"},{"username":"google","password":"test"},{"username":"yahoo","password":"test"},{"username":"hotmail","password":"test"}]}

我想删除这个:

{"username":"google","password":"test"}

来自使用 php 的代码。 我尝试通过将 json 解码为数组来删除,但无法完成。 有什么解决办法吗?

【问题讨论】:

  • 我试过这样做,但它不起作用。 unset($decodedata['Results'](array_search("google",$decodedata['Results']));

标签: php json


【解决方案1】:

老问题,以不同方式格式化 JSON 会有很大帮助。 每个结果条目都应该有一个唯一的键来识别它。 这使得在需要删除或更新该结果时变得容易。 没有理由以这种方式遍历整个 JSON。

代码如下所示

<?php 
 $jsonString = '{"Results":{'
          .'{"username1":{"username":"google","password":"test1"}}'
          .'{"username2":{"username":"yahoo","password":"test2"}}'
          .'{"username3":{"username":"msonline","password":"test3"}}'
          . '}}';
$jsonInPHP = json_decode($jsonString);

$password = $jsonInPHP["username1"]["pasword"];//Returns test1
$username = $jsonInPHP["username1"]["username"];//Returns google

?>

【讨论】:

    【解决方案2】:
    $json_obj = json_decode($json_string);
    $unset_queue = array();
    
    foreach ( $json_obj->Results as $i => $item )
    {
        if ($item->username == "google")
        {
            $unset_queue[] = $i;
        }
    }
    
    foreach ( $unset_queue as $index )
    {
        unset($json_obj->Results[$index]);
    }
    
    // rebase the array
    $json_obj->Results = array_values($json_obj->Results);
    
    $new_json_string = json_encode($json_obj);
    

    【讨论】:

    • +1 用于在 foreach 之外取消设置,以免破坏迭代。聪明!
    • 我不确定 OP 是否想要它,但此版本将在结果中包含数组键,因为键不再串联。例如注意下面的 13"1":{"username":"test","password":"test"},"3":{"username":"yahoo","password":"test"}
    • 这可以通过强制 json_decode 只返回一个关联数组 json_decode($json, true) 来简化。在 foreach 内部对数组进行 unset 应该无关紧要,因为 foreach() 迭代原始数组的副本,因此对原始数组的任何更改都不会修改它正在迭代的副本。
    【解决方案3】:
    <?php
    
      $JSON = '{"Results":['
              . '{"username":"test","password":"test"},'
              . '{"username":"test","password":"test"},'
              . '{"username":"google","password":"test"},'
              . '{"username":"yahoo","password":"test"},'
              . '{"username":"hotmail","password":"test"}'
            . ']}';
    
      // use json_decode to parse the JSON data in to a PHP object
      $jsonInPHP = json_decode($JSON);
    
      // now iterate over the results and remove the one that's google
      $results = count($jsonInPHP->Results);
      for ($r = 0; $r < $results; $r++){
    
        // look for the entry we are trying to find
        if ($jsonInPHP->Results[$r]->username == 'google'
         && $jsonInPHP->Results[$r]->password == 'test'){
    
          // remove the match
          unset($jsonInPHP->Results[$r]);
    
          // now we can either break out of the loop (only remove first match)
          // or you can use subtract one from $r ($r--;) and keep going and
          // find all possible matches--your decision.
          break;
        }
      }
    
      // now that we removed items the keys will be off. let's re-order the keys
      // so they're back in-line
      $jsonInPHP->Results = array_values($jsonInPHP->Results);
    
      // dump the new JSON data, less google's entry
      echo json_encode($jsonInPHP);
    

    这就是我的处理方式。当我需要修改数组本身时,我喜欢避免使用 foreach(...){} 语句。顺便说一句,上面的代码给你留下了:

    {
      "Results":[
        {"username":"test","password":"test"},
        {"username":"test","password":"test"},
        {"username":"yahoo","password":"test"},
        {"username":"hotmail","password":"test"}
      ]
    }
    

    【讨论】:

      【解决方案4】:
      $input='{"Results":[{"username":"test","password":"test"},{"username":"test","password":"test"},{"username":"google","password":"test"},{"username":"yahoo","password":"test"},{"username":"hotmail","password":"test"}]}';
      
      $json = json_decode($input,true);
      $match = array('username'=>'google', 'password'=>'test');
      unset($json['Results'][array_search($match,$json['Results'])]);
      

      在没有 foreach 的情况下执行此操作,但假设您知道要删除的确切值

      【讨论】:

        【解决方案5】:
        $json = '
        {
          "Results":[
            {"username":"test","password":"test"},
            {"username":"test","password":"test"},
            {"username":"google","password":"test"},
            {"username":"yahoo","password":"test"},
            {"username":"hotmail","password":"test"}
          ]
        }';
        
        $arr = json_decode($json, true);
        array_filter($arr, function($v) {
          return !($v['username'] == 'google' && $v['password'] == 'test');
        });
        $json = json_encode($arr);
        

        【讨论】:

        • 我不想使用 [2],因为我无法计算出价值
        • @codecute:我在你的问题中没有看到这个要求。我现在用array_filter 替换了我的代码中的那一行,只过滤用户名是google 和密码是test 的条目。希望有帮助
        【解决方案6】:
        $myArray=json_decode($theJSONstring);
        unset($myArray['Results'][2]);
        

        【讨论】:

          猜你喜欢
          • 2015-03-16
          • 2015-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多