1 回答
TA贡献1789条经验 获得超10个赞
您的 JSON 存在一些问题,所以我已经更正了这些问题,主要问题是您使用in_array()它只是告诉您它在数组中而不是在哪里。因此,在第一个版本中,我将array_search()其更改为,然后告诉您它在哪里。
$flav = $_GET['flav'];
$json = '[{
"flavor": "chocolate",
"type": "hard",
"instock": true
}, {
"flavor": "vanilla",
"type": "hard",
"instock": false
}, {
"flavor": "strawberry",
"type" : "soft",
"instock": true
}, {
"flavor": "mint",
"type": "hard",
"instock": true
}]';
$decode = json_decode($json);
if(($key = array_search($flav, array_column($decode, 'flavor'))) !== false) {
print "flavor - ". $decode[$key]->flavor.PHP_EOL
. "type - ". $decode[$key]->type.PHP_EOL
. "instock - ". $decode[$key]->instock.PHP_EOL;
} else {
print 'Invalid flavor';
}
我还完成了第二个版本,它使用作为索引的风味重新索引数组,因此您可以直接访问它...
// Decode to an array
$decode = json_decode($json, true);
// Create a new version of the array indexed by the flavor
$decode = array_column($decode, null, "flavor");
// Check if it is in the array
if ( isset ($decode[$flav]) ){
// Directly output the data
print "flavor - ". $decode[$flav]["flavor"].PHP_EOL
. "type - ". $decode[$flav]["type"].PHP_EOL
. "instock - ". $decode[$flav]["instock"].PHP_EOL;
} else {
print 'Invalid flavor';
}
- 1 回答
- 0 关注
- 131 浏览
添加回答
举报