猿问

如果结果存在,则获取 JSON 节点

我需要根据值是否存在来获取 JSON 节点的值


我想出了如何检测 JSON 中是否存在风味,现在我只需要获取该节点内的所有信息


$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(in_array($flav, array_column($decode, 'flavor'))) {

  print flavor . ' - ' . type . ' - ' . instock;

} else {

  print 'Invalid flavor';

}


饮歌长啸
浏览 132回答 1
1回答

至尊宝的传说

您的 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 arrayif ( 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';}
随时随地看视频慕课网APP
我要回答