我有以下数组,当我执行print_r(array_values($get_user));时,我得到:

Array (
          [0] => 10499478683521864
          [1] => 07/22/1983
          [2] => email@saya.com
          [3] => Alan [4] => male
          [5] => Malmsteen
          [6] => https://www.facebook.com  app_scoped_user_id/1049213468352864/
          [7] => stdClass Object (
                   [id] => 102173722491792
                   [name] => Jakarta, Indonesia
          )
          [8] => id_ID
          [9] => El-nino
          [10] => Alan El-nino Malmsteen
          [11] => 7
          [12] => 2015-05-28T04:09:50+0000
          [13] => 1
        )

我试图按如下方式访问数组:
echo $get_user[0];

但这显示了我:



注意:

我从 Facebook SDK 4 获得此数组,所以我不知道原始的数组结构。

作为示例,我如何从数组中访问email@saya.com值?

最佳答案

要访问arrayobject,您如何使用两个不同的运算符。

Arrays

要访问数组元素,您必须使用[]或使用不多的元素,但也可以使用{}

echo $array[0];
echo $array{0};
//Both are equivalent and interchangeable

声明数组和访问数组元素之间的区别

定义数组和访问数组元素是两件事。所以不要把它们混在一起。

要定义一个数组,可以使用array()或对于PHP> = 5.4 [],可以分配/设置一个数组/元素。如上所述,当您使用[]{}访问数组元素时,您将获得与设置元素相反的数组元素的值。
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4

//Accessing an array element
echo $array[0];
echo $array{0};

Access array element

To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:

$array[(Any expression)]

So just be aware of what expression you use as key and how it gets interpreted by PHP:

echo $array[0];            //The key is an integer; It accesses the 0's element
echo $array["0"];          //The key is a string; It accesses the 0's element
echo $array["string"];     //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT];     //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT];     //The key is also a constant and not a string
echo $array[$anyVariable]  //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function

Access multidimensional array

If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].

echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
         // ├─────────────┘  ├──────────────┘  ├────────────────────────────┘
         // │                │                 └── 3rd Array dimension;
         // │                └──────────────────── 2d  Array dimension;
         // └───────────────────────────────────── 1st Array dimension;

Objects

要访问对象属性,必须使用->
echo $object->property;

If you have an object in another object you just have to use multiple -> to get to your object property.

echo $objectA->objectB->property;



数组与对象

现在,如果您将数组和对象彼此混合在一起,则只需查看是否现在访问数组元素或对象属性并为其使用相应的运算符即可。
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
    //├────┘  ├───────────┘  ├───────────┘ ├──────────────────────┘   ├──────┘
    //│       │              │             │                          └── property ;
    //│       │              │             └───────────────────────────── array element (object) ; Use -> To access the property 'property'
    //│       │              └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
    //│       └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
    //└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'


//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
    //├───┘ ├────────────┘  ├──────────────┘   ├────┘  ├──────┘ ├───────┘
    //│     │               │                  │       │        └── array element ;
    //│     │               │                  │       └─────────── property (array) ; Use [] To access the array element 'element'
    //│     │               │                  └─────────────────── property (object) ; Use -> To access the property 'property'
    //│     │               └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
    //│     └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
    //└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'

I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.

Arrays, Objects and Loops

If you don't just want to access a single element you can loop over your nested array / object and go through the values of a particular dimension.

For this you just have to access the dimension over which you want to loop and then you can loop over all values of that dimension.

As an example we take an array, but it could also be an object:

Array (
    [data] => Array (
            [0] => stdClass Object (
                    [propertyXY] => 1
                )
            [1] => stdClass Object (
                    [propertyXY] => 2
                )
            [2] => stdClass Object (
                    [propertyXY] => 3
               )
        )
)

如果在第一个维度上循环,则将从第一个维度获取所有值:
foreach($array as $key => $value)

Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):

Array (  //Key: array
    [0] => stdClass Object (
            [propertyXY] => 1
        )
    [1] => stdClass Object (
            [propertyXY] => 2
        )
    [2] => stdClass Object (
            [propertyXY] => 3
        )
)

如果在第二维上循环,则将从第二维获取所有值:
foreach($array["data"] as $key => $value)

Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):

stdClass Object (  //Key: 0
    [propertyXY] => 1
)
stdClass Object (  //Key: 1
    [propertyXY] => 2
)
stdClass Object (  //Key: 2
    [propertyXY] => 3
)

这样一来,您就可以遍历任何维,无论它是数组还是对象。

分析 var_dump() / print_r() / var_export() 输出

所有这3个调试功能都输出相同的数据,只是以另一种格式或带有一些元数据(例如,类型,大小)。因此,在这里我想展示如何读取这些函数的输出,以了解/了解如何从数组/对象访问某些数据。

输入数组:
$array = [
    "key" => (object) [
        "property" => [1,2,3]
    ]
];
var_dump()输出:
array(1) {
  ["key"]=>
  object(stdClass)#1 (1) {
    ["property"]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
    }
  }
}
print_r()输出:
Array
(
    [key] => stdClass Object
        (
            [property] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

        )

)
var_export()输出:
array (
  'key' =>
  stdClass::__set_state(array(
     'property' =>
    array (
      0 => 1,
      1 => 2,
      2 => 3,
    ),
  )),
)

因此,您可以看到所有输出都非常相似。而且,如果现在要访问值2,则可以从值本身开始,您要访问该值,然后逐步到达“左上角”。

1.我们首先看到,值2在键为1的数组中
array(3) {  //var_dump()
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
Array  //print_r()
(
  [0] => 1
  [1] => 2
  [2] => 3
)
array (  //var_export()
  0 => 1,
  1 => 2,
  2 => 3,
),

This means we have to use []/{} to access the value 2 with [1], since the value has the key/index 1.

2. Next we see, that the array is assigned to a property with the name property of an object

object(stdClass)#1 (1) {  //var_dump()
  ["property"]=>
    /* Array here */
}
stdClass Object  //print_r()
(
  [property] => /* Array here */
)
stdClass::__set_state(array(  //var_export()
  'property' =>
    /* Array here */
)),

This means we have to use -> to access the property of the object, e.g. ->property.

So until now we know, that we have to use ->property[1].

3. And at the end we see, that the outermost is an array

array(1) {  //var_dump()
  ["key"]=>
    /* Object & Array here */
}
Array  //print_r()
(
  [key] =>
    /* Object & Array here */
)
array (  //var_export()
  'key' =>
    /* Object & Array here */
)

As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:

echo $array["key"]->property[1];

输出将是:
2

不要让PHP欺骗您!

您需要了解一些事情,这样您就不必花费大量时间在上面就可以找到它们。
  • “隐藏”字符

    有时,您的按键中包含字符,这些字符在浏览器的第一次外观中不会出现。然后您要问自己,为什么无法访问该元素。这些字符可以是:制表符(\t),换行(\n),空格或html标签(例如</p><b>)等。

    例如,如果查看print_r()的输出,您将看到:
    Array ( [key] => HERE )
    

    然后,您尝试通过以下方式访问元素:
    echo $arr["key"];
    

    但是您会收到通知:



    这很好地表明必须有一些隐藏的字符,因为即使键看起来很正确,也无法访问该元素。

    这里的技巧是使用var_dump() +查看您的源代码! (可选:highlight_string(print_r($variable, TRUE));)

    突然之间,您可能会看到以下内容:
    array(1) {
      ["</b>
    key"]=>
      string(4) "HERE"
    }
    

    现在您将看到,您的键中带有html标记+一个换行符,由于print_r()和浏览器没有显示该字符,因此您一开始就没有看到它。

    所以现在,如果您尝试执行以下操作:
    echo $arr["</b>\nkey"];
    

    您将获得所需的输出:
    HERE
    
  • 如果您查看XML,请不要信任print_r()var_dump()的输出

    您可能已将XML文件或字符串加载到对象中,例如
    <?xml version="1.0" encoding="UTF-8" ?>
    <rss>
        <item>
            <title attribute="xy" ab="xy">test</title>
        </item>
    </rss>
    

    现在,如果您使用var_dump()print_r(),您将看到:
    SimpleXMLElement Object
    (
        [item] => SimpleXMLElement Object
        (
            [title] => test
        )
    
    )
    

    如您所见,您看不到title的属性。因此,正如我所说,当您拥有XML对象时,请不要相信var_dump()print_r()的输出。始终使用 asXML() 查看完整的XML文件/字符串。

    因此,只需使用下面显示的方法之一:
    echo $xml->asXML();  //And look into the source code
    
    highlight_string($xml->asXML());
    
    header ("Content-Type:text/xml");
    echo $xml->asXML();
    

    然后您将获得输出:
    <?xml version="1.0" encoding="UTF-8"?>
    <rss>
        <item>
            <title attribute="xy" ab="xy">test</title>
        </item>
    </rss>
    


  • 有关更多信息,请参见:

    常规(符号,错误)
  • Reference - What does this symbol mean in PHP?
  • Reference - What does this error mean in PHP?
  • PHP Parse/Syntax Errors; and How to solve them?

  • 属性名称问题
  • How can I access a property with an invalid name?
  • How to access object properties with names like integers?
  • 10-05 21:18
    查看更多