JSON响应如下所示:
{
"success": true,
"ownersList": [
{ "propertiesList": [],
"email": "email@email.com" },
{ "propertiesList": [],
"email": "email2@email.com" }
]
}
如何获取与特定"email"值相关的所有propertiesList
?
我不认为你需要任何花哨的Laravel来做到这一点。你可能会想使用Guzzle(这是一个依赖于Laravel),因为它是一个很好的和简单的PHP CURL包装器。
// assumes the API response is in variable $api_response_body_as_a_string
$o_api_response = json_decode($api_response_body_as_a_string);
$owners_list = $o_api_response->owners_list;
$propertiesList = NULL;
foreach($owners_list as $this_owner) {
if('email@to.find' === $this_owner->email) {
$propertiesList = $this_owner->$propertiesList;
break;
}
}
// $propertiesList has the result or is NULL
原问题(OP澄清前):
你目前在你的问题中没有任何与Laravel相关的代码,所以我冒昧地猜测你正在查询一个表,其中propertiesList是ownersList模型的外键:http://laravel.com/docs/eloquent立即加载
否则,需要更多关于您的设置(模型和关系)的信息来帮助您。
您可以尝试这样做:
$obj = json_decode($json);
$item = null;
array_walk($obj->ownersList, function($i) use (&$item) {
if($i->email == 'email@email.com') $item = $i;
});
// Print out the item
dd($item);
我使用了硬编码的'email@email.com'
,你可以使用变量或任何你有的东西
我知道这个问题很老了,已经有答案了,但是使用Laravel的一个很好的干净的方法是这样做:
$json = json_decode($response, true);
$properties = collect($json['ownersList'])
->where('email', 'email@email.com')
->pluck('propertiesList')->all();
在内部,它做的事情与其他问题相似,但它更流畅,更容易阅读和理解。
查看Collection文档获取更多信息。