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

在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♦

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题