如何使用PHP从数组中删除JSON密钥?

时间:2017-10-18 14:43:51

标签: php json

我有以下数组,我希望能够删除所有" phonenumber"键,当然还有JSON对象的值。只有键" phonenumber"不是整个对象。我怎样才能做到这一点?

null

2 个答案:

答案 0 :(得分:4)

// make array
$array = json_decode($your_json_string, true);

// loop through array
foreach($array as $key => $item){
       // unset them
       unset($array[$key]["phonenumber"]);
}

// make json again
$json_string_modified = json_encode($array);

或使用参考

// make array
$array = json_decode($your_json_string, true);

// loop through array using reference
foreach($array as &$item){

      // unset specific key
      unset($item["phonenumber"]);

}

// unset reference
unset($item);

// make json again
// you may remove JSON_PRETTY_PRINT flag, I kept it just to see o/p
$json_string_modified = json_encode($array,JSON_PRETTY_PRINT);

答案 1 :(得分:1)

$jsonArray=json_decode($data);
//Remove unvanted props
foreach ($jsonArray as $key=>$row) {

   foreach ($row as $prop=>$field) {
       if ($prop != 'phonenumber')
           $newArray[$key][$prop] = $field;
       }

}

 $jsonArray=json_encode($newArray);