如何从PHP中提取多个JSON对象并用PHP数组? [英] How do I extract multiple JSON objects from and array with PHP?
本文介绍了如何从PHP中提取多个JSON对象并用PHP数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试找出如何从json数组中提取多个JSON对象.
i've been trying to figure out how to extract multiple JSON objects from a json array.
我在其他帖子中使用了此代码
I used this code from other post
$json = '[
{"user_id":"1",
"user_name":"Sayeed Amin",
"time":"2019-11-06 13:21:26"}
]';
$someArray = json_decode($json, true);
foreach ($someArray as $key => $value) {
echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}
我可以将其用于数组内的单个json对象,效果很好.
I can use this for a single json object inside an array, the result is good.
结果: 1,Sayeed Amin,2019-11-06 13:21:26
如果我在数组和数组中有多个json对象,该怎么办?喜欢
How about if i have multiple json objects inside and array? like
$json = '[
{"name":"Name",
"value":"me you",
"id":0,
"type":"name",
"first":"me",
"middle":"",
"last":"you"
},
{"name":"Email",
"value":"myemail@gmail.com",
"id":1,
"type":"email"
},
{"name":"Phone",
"value":"+12015550000",
"id":2,"type":"phone"
},
{"name":"Address",
"value":"my address\nsomecity, somestate\nsomepost\nUS",
"id":3,
"type":"address",
"address1":"my address",
"address2":"",
"city":"somecity",
"state":"somestate",
"postal":"somepost",
"country":"US"
}
]';
$someArray = json_decode($json, true);
foreach ($someArray as $key => $value) {
echo $value["name"] . ", " . $value["value"] . "<br>";
}
结果:名字,我,你
电子邮件,myemail @ gmail.com
电话,+ 12015550000
地址,我的地址,某个城市,某个州,某个职位,美国
所需结果:我叫你,
推荐答案
如果您只想输出对象数组的首次出现,则可以像这样对数组进行适当寻址
If you only want to output the First Occurance of the array of objects then address the array appropriately like
$json = '[
{"name":"Name",
"value":"me you",
"id":0,
"type":"name",
"first":"me",
"middle":"",
"last":"you"
},
{"name":"Email",
"value":"myemail@gmail.com",
"id":1,
"type":"email"
},
{"name":"Phone",
"value":"+12015550000",
"id":2,"type":"phone"
},
{"name":"Address",
"value":"my address\nsomecity, somestate\nsomepost\nUS",
"id":3,
"type":"address",
"address1":"my address",
"address2":"",
"city":"somecity",
"state":"somestate",
"postal":"somepost",
"country":"US"
}
]';
$arr = json_decode($json);
echo $arr[0]->name . ", " . $arr[0]->value . "\n";
结果
Name, me you
这篇关于如何从PHP中提取多个JSON对象并用PHP数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文