简体   繁体   English

如何使用键而不是数组索引从 JSON 数组中获取值

[英]How to get the value from a JSON array using the key instead of array index

I have a JSON that I can comfortably get the values from.我有一个 JSON,我可以轻松地从中获取值。

However, on the array part, I'd want to get the values using the value instead of the index.但是,在数组部分,我想使用值而不是索引来获取值。

$st = '{
   "Body":{
      "stkCallback":{
         "MerchantRequestID":"10832-3081608-1",
         "ResultCode":0,
         "ResultDesc":"The service request is processed successfully.",
         "CallbackMetadata":{
            "Item":[
               {
                  "Name":"Amount",
                  "Value":2.0
               },
               {
                  "Name":"ReceiptNumber",
                  "Value":"OEH49B3LZU"
               }
            ]
         }
      }
   }
}';

$callbackData = json_decode($st);
echo $callbackData->Body->stkCallback->CallbackMetadata->Item[0]->Value; //works well but this index number could change
echo $callbackData->Body->stkCallback->CallbackMetadata->Item[1]->Value; //works well but this index number could change

Can I get the values using say Amount and ReceiptNumber instead of the index as above?我可以使用AmountReceiptNumber而不是上面的索引来获取值吗?

If you are just fetching odd values (1 or 2) then you can loop through the items and compare the name with the one you are after, then you can extract the corresponding value...如果您只是获取奇数值(1 或 2),那么您可以遍历这些项目并将名称与您之后的名称进行比较,然后您可以提取相应的值......

$name = "Amount";
foreach ( $callbackData->Body->stkCallback->CallbackMetadata->Item as $item )   {
    if ( $item->Name == $name ) {
        echo $item->Value;
    }
}

If there was a block of data and you want to use it in various places, it's quicker to extract the values (using array_column() ) and index it by the name...如果有一个数据块并且您想在不同的地方使用它,那么提取值(使用array_column() )并按名称对其进行索引会更快......

$data = array_column($callbackData->Body->stkCallback->CallbackMetadata->Item, 
           "Value", "Name");
print_r($data);

This for your example data gives...这对于您的示例数据给出...

Array
(
    [Amount] => 2
    [ReceiptNumber] => OEH49B3LZU
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM