简体   繁体   English

PHP 从嵌套的 JSON 数组中检索值

[英]PHP Retrieve Value from Nested JSON Array

I'm working with the following JSON Object:我正在使用以下 JSON Object:

    {
  "body": {
    "subject": "Lorem ipsum dolor sit amet, consectetur adipiscing elit", 
    "to": [
      {
        "location": "Hawthorne, CA", 
        "name": "Jeff Daniels", 
        "phoneNumber": "+15552123456", 
        "target": true
      }
    ], 
    "type": "SMS"
  }, 
  "uuid": "5797377010673708914"
}

I'm trying to retrieve certain values and can't work out the syntax to get the to phoneNumber value.我正在尝试检索某些值,但无法计算出获取 to phoneNumber 值的语法。 Here's what I'm doing so far:到目前为止,这是我正在做的事情:

$webhook= json_decode( $webhookJSON, TRUE );
$subject = $webhook['body']['subject'];
$toPhoneNumber = $webhook['body']['to']['phoneNumber'];

I'm getting the $subject but not the $toPhoneNumber .我得到$subject但不是$toPhoneNumber I've tried adding [0] in a few places to get the first member of the array but this isn't working either and at this stage I'm stumped as to how I can get the to phoneNumber value from the nested array.我尝试在几个地方添加[0]以获取数组的第一个成员,但这也不起作用,在这个阶段,我很难理解如何从嵌套数组中获取 to phoneNumber 值。

You were on the correct way with adding [0] to it.您添加[0]的方式是正确的。 I highly suggest, that you should use print_r() to double check the structure of the array, if your are unsure.我强烈建议,如果您不确定,您应该使用print_r()仔细检查数组的结构。 It would give you this:它会给你这个:

Array
(
    [body] => Array
        (
            [subject] => Lorem ipsum dolor sit amet, consectetur adipiscing elit
            [to] => Array
                (
                    [0] => Array
                        (
                            [location] => Hawthorne, CA
                            [name] => Jeff Daniels
                            [phoneNumber] => +15552123456
                            [target] => 1
                        )

                )

            [type] => SMS
        )

    [uuid] => 5797377010673708914
)

As you can see, you can acces the phonenumber via如您所见,您可以通过以下方式访问电话号码

$toPhoneNumber = $webhhok['body']['to'][0]['phoneNumber'];

The reason is, that you start an array within the json, everytime you use [] .原因是,每次使用[]时,您都会在 json 中启动一个数组。 That's why you need to use an index to access the element.这就是为什么您需要使用索引来访问元素的原因。

When you are in charge of the json, I would recommend to remove the array, because you don't need it there, unless you want to have multiple receipients:当您负责 json 时,我建议您移除阵列,因为您不需要它,除非您想要有多个接收者:

{
  "body": {
    "subject": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
    "to": {
      "location": "Hawthorne, CA",
      "name": "Jeff Daniels",
      "phoneNumber": "+15552123456",
      "target": true
    },
    "type": "SMS"
  },
  "uuid": "5797377010673708914"
}

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

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