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

如何根据子值查找json直接父级

如何根据子值查找json直接父级

PHP
守候你守候我 2021-11-13 19:11:28
我需要使用 PHP 在 JSON 文件中找到所有 "type": "featured-product" 实例的直接父级。将此父字符串存储在变量中。使用 foreach。在下面的示例中,变量的值为“1561093167965”和“3465786822452”我有点失落,谢谢你的帮助!{    "current": {        "sections": {            "1561093167965": {                "type": "featured-product"            },            "3465786822452": {                "type": "featured-product"            }        }      }}foreach ($json['current']['sections'] as $sectionName => $section) {    if ($section['type'] && $section['type'] == 'featured-product') {      $featuredId = $sectionName;    }}
查看完整描述

3 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

您可以采用的另一种方法是创建一个仅包含featured-productsusing的新数组array_filter,然后提取密钥。从文档:


如果回调函数返回 TRUE,则将数组中的当前值返回到结果数组中。保留数组键。


$product_sections = array_keys(

    array_filter($json['current']['sections'], function($val) {

        return $val['type'] === 'featured-product';

}));

原始代码中的问题是您的$featuredId变量在循环的每次迭代中都被覆盖,因此当它结束时,它的值将是最后处理的元素之一。如果必须处理多个值,则必须将其添加到数组中或直接在foreach. 您可以查看有关如何修复代码的其他答案。


查看完整回答
反对 回复 2021-11-13
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

可能有一种更简洁的方法,但这可以使用 json_decode 并使用 foreach 迭代数组


$json='{

    "current": {

        "sections": {

            "1561093167965": {

                "type": "featured-product"

            },

            "3465786822452": {

                "type": "featured-product"

            }

        }  

    }

}';

$e=json_decode($json,true);


foreach($e['current']['sections'] as $id=>$a){


if($a['type']=='featured-product'){

echo 'the parent id is '.$id;


}


}


查看完整回答
反对 回复 2021-11-13
?
慕沐林林

TA贡献2016条经验 获得超9个赞

//change this with the real json

$json='{

    "current": {

        "sections": {

            "1561093167965": {

                "type": "featured-product"

            },

            "3465786822452": {

                "type": "featured-product"

            }

        }  

    }

}';


$result = [];

$jsond=json_decode($json,true);

foreach($jsond['current']['sections'] as $k=>$v){

   if($v['type']=='featured-product'){

$result[] = $k;


 }


}


查看完整回答
反对 回复 2021-11-13
  • 3 回答
  • 0 关注
  • 120 浏览

添加回答

举报

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