3 回答

TA貢獻1827條經驗 獲得超8個贊
您可以采用的另一種方法是創建一個僅包含featured-productsusing的新數組array_filter,然后提取密鑰。從文檔:
如果回調函數返回 TRUE,則將數組中的當前值返回到結果數組中。保留數組鍵。
$product_sections = array_keys(
array_filter($json['current']['sections'], function($val) {
return $val['type'] === 'featured-product';
}));
原始代碼中的問題是您的$featuredId變量在循環的每次迭代中都被覆蓋,因此當它結束時,它的值將是最后處理的元素之一。如果必須處理多個值,則必須將其添加到數組中或直接在foreach. 您可以查看有關如何修復代碼的其他答案。

TA貢獻1839條經驗 獲得超15個贊
可能有一種更簡潔的方法,但這可以使用 json_decode 并使用 foreach 迭代數組
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$e=json_decode($json,true);
foreach($e['current']['sections'] as $id=>$a){
if($a['type']=='featured-product'){
echo 'the parent id is '.$id;
}
}

TA貢獻2016條經驗 獲得超9個贊
//change this with the real json
$json='{
"current": {
"sections": {
"1561093167965": {
"type": "featured-product"
},
"3465786822452": {
"type": "featured-product"
}
}
}
}';
$result = [];
$jsond=json_decode($json,true);
foreach($jsond['current']['sections'] as $k=>$v){
if($v['type']=='featured-product'){
$result[] = $k;
}
}
- 3 回答
- 0 關注
- 153 瀏覽
添加回答
舉報