gpt4 book ai didi

php - 如何使用 PHP 从数组中删除 JSON 键?

转载 作者:行者123 更新时间:2023-12-02 15:06:26 25 4
gpt4 key购买 nike

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

[
{
"role": "admin",
"id": "59df4ef2d8d39",
"email": "a@a.dk",
"name": "A",
"lastname": "A",
"password": "1",
"image": "img_webshop\/userimage-59dfb91515810.png"
},
{
"role": "user",
"id": "59df4f1b070e6",
"phonenumber": "12345678",
"name": "B",
"lastname": "B",
"password": "2",
"image": "img_webshop\/userimage-59e37de69475b.png"
},
{
"role": "user",
"id": "59dfc0cb07985",
"email": "c@c.dk",
"name": "C",
"lastname": "C",
"password": "3",
"image": "img_webshop\/userimage-59dfc0cb06c5f.png"
},
{
"role": "user",
"id": "59dfc22f26f78",
"phonenumber": "87654321",
"name": "D",
"lastname": "D",
"password": "4",
"image": "img_webshop\/userimage-59dfc22f2638d.png"
},
{
"role": "user",
"id": "59dfc460b261e",
"email": "e@e.dk",
"name": "E",
"lastname": "E",
"password": "5",
"image": "img_webshop\/userimage-59dfc460af866.png"
}
]

最佳答案

// 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);

关于php - 如何使用 PHP 从数组中删除 JSON 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46812942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com