3 回答

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

TA貢獻(xiàn)1839條經(jīng)驗 獲得超15個贊
可能有一種更簡潔的方法,但這可以使用 json_decode 并使用 foreach 迭代數(shù)組
$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貢獻(xiàn)2016條經(jīng)驗 獲得超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 關(guān)注
- 144 瀏覽
添加回答
舉報