Rak*_*tra 0 php arrays json object
我有一个JSON字符串,如下面给出的存储在其中的字符串$json.我想在category_id不使用循环的情况下访问第一个.我该如何访问它?
$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);
Run Code Online (Sandbox Code Playgroud)
试试下面的代码.
$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'];
Run Code Online (Sandbox Code Playgroud)
产量
women_jeans
women_tops
Run Code Online (Sandbox Code Playgroud)
您还可以使用以下功能查找特定值.
$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);
Run Code Online (Sandbox Code Playgroud)
产量
women_jeans
Run Code Online (Sandbox Code Playgroud)
如果你想在没有循环的情况下获得category_id,true那么请在下面使用.
$array = $outfits->outfits[0]->{1};
$category1 = $array[0]->category_id;
Run Code Online (Sandbox Code Playgroud)