如果我不使用正确的术语,我很抱歉,我还在学习。我试图找出如何搜索具有嵌套数组的JSON数组中的特定值,然后返回一个关联的值。
我的问题类似于StackOverflow(How to search through a JSON Array in PHP)上的这个回答问题,但我希望能够在人或狗或任何其他嵌套数组中通过id找到一个项目。基本上我想将foreach中的people
转换为通配符。
这是我的JSON数据 - http://foothillertech.com/student/webdesign/2018/2018benrud2/tinker/dataIntro2/test/data.json
foreach($json->people as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
任何帮助是极大的赞赏。
在这种情况下,只需做两个循环。
$json = json_decode('{
"people": [
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
],
"dogs": [
{
"id": "8081",
"content": "spot"
},
{
"id": "8091",
"content": "max"
}
]
}');
foreach($json as $key=>$value){
//$key = people or dogs
//$value = stdClass()
foreach($value as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
}
产量
bar
如果我们使用8081
而不是8097
,我希望得到'spot`。并测试,我确实得到了(在狗身上)。
如果id在数据中是唯一的,则可以合并内部数组并按id索引它们。
$data = json_decode($json, true);
$merged = array_merge(...array_values($data));
$indexed = array_column($merged, null, 'id');
然后你可以按id查找任何项目。
echo $indexed['8097']['content'] ?? 'not found';
仅当id是唯一的时才有效。如果不是,则按id索引将导致数据丢失。