嘗試以下代碼。
$json = '{"outfits": [{"1": [{"category_id": "women_jeans", "product_id": 464540467}, {"category_id": "women_tops", "product_id": 487351815}, {"category_id": "women_coats", "product_id": 493322686}, {"category_id": "women_bags", "product_id": 483902882}, {"category_id": "women_shoes", "product_id": 492772225}]}]}';
$outfits = json_decode($json,true);
echo "Category 1: ".$outfits["outfits"][0][1][0]['category_id'];
echo "Category 2: ".$outfits["outfits"][0][1][1]['category_id'];
輸出
women_jeans
women_tops
您也可以使用以下功能查找特定的值。
$array = $outfits["outfits"][0][1];
$key = "product_id";
$val = "464540467";
function whatever($array, $key, $val) {
foreach ($array as $item)
if (isset($item[$key]) && $item[$key] == $val)
echo $item['category_id'];
return false;
}
whatever($array,$key,$val);
輸出
women_jeans
如果你想獲得無CATEGORY_ID環和true
然後用下面。
$array = $outfits->outfits[0]->{1};
$category1 = $array[0]->category_id;
你有多個'category_id'可利用的。哪一個你到底要訪問? – Nikola
@Nikola:第一個有product_id:464540467 –
$ outfits = json_decode($ json,true); var_dump($ outfits ['outfits'] [0] [1] [0] [「category_id」]); –