There are some issues with your JSON, so I've corrected those and the main problem is that you use in_array()
which just tells you it is in the array and not where. So in the first version I've changed this to array_search()
which then tells you where it is.
$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';
}
I've also done a second version which re-indexes the array with flavor as the index and so you can directly access it...
// 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';
}