doumei4964 2019-05-23 07:27
浏览 231
已采纳

在PHP中通过键删除JSON子项

My goal is to have a function that can remove a specified json child, which could also be nested inside deeper.

My function looks like this:

private function removeJsonChild(String $jsonKey, String $jsonString)
{
    $json = json_decode($jsonString, true);
    $arr_index = array();

    foreach ($json as $key => $value) {
        if (is_array($value)) {
            $json[$key] = $this->removeJsonChild($jsonKey, json_encode($value));
        }

        if ($key == $jsonKey) {
            $arr_index[] = $key;
        }
    }

    foreach ($arr_index as $i) {
        unset($json[$i]);
    }

    return json_encode($json);
}

The function would work if i wouldn't check if a $value is an array and then call the function again recursively. But there is the problem i think. In the statement where i assign the return value of the function to $json[$key]. What am i doing wrong?

EDIT: definitely forgot a json_decode. New code looks like this:

private function removeJsonChild(String $jsonKey, String $jsonString)
{
    $json = json_decode($jsonString, true);
    $arr_index = array();

    foreach ($json as $key => $value) {
        if (is_array($value)) {
            $json[$key] = json_decode($this->removeJsonChild($jsonKey, json_encode($value)));
        }

        if ($key == $jsonKey) {
            $arr_index[] = $key;
        }
    }

    foreach ($arr_index as $i) {
        unset($json[$i]);
    }

    return json_encode($json);
}

EDIT2:

The function works now, however it slightly changes the json schema.

An JSON like this:

[
  {
    "id": 1,
    "name": "oyzadsaigny647"
  }
]

now becomes this:

{
  "1": {
    "id": 1,
    "name": "oyzadsaigny647"
  }
}
  • 写回答

1条回答 默认 最新

  • dougaicha5258 2019-05-23 07:52
    关注
    private function removeJsonChild(String $jsonKey, String $jsonString) {
    
       $data = json_decode($jsonString, true);
    
       $data = $this->removeKeyFromArray($key, $data);
    
       return json_encode($data);
    
    }
    
    private function removeKeyFromArray(String $deleteKey, array $data) {
    
      unset($data[$deleteKey]); // No need to check if it exists, it just does nothing in that case
    
      foreach($data as $key => value) {
        if(is_array($value)) {
            $data[$key] = $this->removeKeyFromArray($deleteKey, $value);
        }
      }
      return $data;
    }
    

    NOTE: this will work in case of dictionaries, i.e. array with actual keys. If you have a plain array such as [1, 10, 23, 15] the unset behaviour is wrong, as pointed out by @deceze♦

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率