为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
饮歌长啸 2021-11-19 16:34:34
我需要根据值是否存在来获取 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';}
查看完整描述

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';

}


查看完整回答
反对 回复 2021-11-19
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信