猿问

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

我需要使用 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;

    }

}


守候你守候我
浏览 121回答 3
3回答

慕仙森

您可以采用的另一种方法是创建一个仅包含featured-productsusing的新数组array_filter,然后提取密钥。从文档:如果回调函数返回 TRUE,则将数组中的当前值返回到结果数组中。保留数组键。$product_sections = array_keys(    array_filter($json['current']['sections'], function($val) {        return $val['type'] === 'featured-product';}));原始代码中的问题是您的$featuredId变量在循环的每次迭代中都被覆盖,因此当它结束时,它的值将是最后处理的元素之一。如果必须处理多个值,则必须将其添加到数组中或直接在foreach. 您可以查看有关如何修复代码的其他答案。

紫衣仙女

可能有一种更简洁的方法,但这可以使用 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;}}

慕沐林林

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