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 關注
- 149 瀏覽
添加回答
舉報