亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何根據子值查找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 關注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號