如何访问数组/对象? [英] How can I access an array/object?

查看:22
本文介绍了如何访问数组/对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following array and when I do print_r(array_values($get_user));, I get:

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];

但这显示我:

未定义 0

注意:

我从 Facebook SDK 4 得到这个数组,所以我不知道原始数组结构.

I get this array from the Facebook SDK 4, so I don't know the original array structure.

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

How can I access as an example the value email@saya.com from the array?

推荐答案

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

To access an array or object you how to use two different operators.

要访问数组元素,您必须使用 [].

To access array elements you have to use [].

echo $array[0];

在较旧的 PHP 版本上,还允许使用 {} 的替代语法:

On older PHP versions, an alternative syntax using {} was also allowed:

echo $array{0};

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

定义数组和访问数组元素是两件事.所以不要混淆它们.

Difference between declaring an array and accessing an array element

Defining an array and accessing an array element are two different things. So don't mix them up.

要定义一个数组,您可以使用 array() 或 PHP >=5.4 [] 并分配/设置一个数组/元素.如上所述,当您使用 [] 访问数组元素时,您将获得与设置元素相反的数组元素的值.

To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.

//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];

访问数组元素

要访问数组中的特定元素,您可以使用 []{} 中的任何表达式,然后计算您要访问的键:

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)]

因此,请注意您用作键的表达式以及它如何被 PHP 解释:

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

访问多维数组

如果你有多个数组,你就只有一个多维数组.要访问子数组中的数组元素,您只需使用多个 [].

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

对象

要访问对象属性,您必须使用 ->.

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;

注意:

  1. 另外,如果你有一个无效的属性名称,你必须小心!因此,要查看所有问题,您可能会遇到无效的属性名称,请参阅此问题/答案.尤其是这个,如果您在属性名称的开头有数字.

  1. Also you have to be careful if you have a property name which is invalid! So to see all problems, which you can face with an invalid property name see this question/answer. And especially this one if you have numbers at the start of the property name.

您只能访问具有公共可见性的属性从课外.否则(私有的或受保护的)你需要一个方法或反射,你可以用它来获取属性的值.

You can only access properties with public visibility from outside of the class. Otherwise (private or protected) you need a method or reflection, which you can use to get the value of the property.

数组和对象

现在,如果您将数组和对象混合在一起,您只需查看您现在是否访问数组元素或对象属性并为其使用相应的运算符.

Arrays & Objects

Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.

//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.

注意:

  1. 是否称为数组或对象取决于变量的最外层部分.所以 [new StdClass] 是一个 array,即使它内部有(嵌套)对象并且 $object->property = array(); 是一个对象,即使它内部有(嵌套)数组.

  1. If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.

如果您不确定是否有对象或数组,只需使用 gettype().

如果有人使用与您不同的编码风格,请不要感到困惑:

Don't get yourself confused if someone uses another coding style than you:

 //Both methods/styles work and access the same data
 echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
 echo $object->
        anotherObject
        ->propertyArray
        ["elementOneWithAnObject"]->
        property;

 //Both methods/styles work and access the same data
 echo $array["arrayElement"]["anotherElement"]->object->property["element"];
 echo $array["arrayElement"]
     ["anotherElement"]->
         object
   ->property["element"];

数组、对象和循环

如果您不只是想访问单个元素,您可以遍历嵌套数组/对象并遍历特定维度的值.

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                   
               )    
        )
)

如果您遍历第一维,您将获得第一维的所有值:

If you loop over the first dimension you will get all values from the first dimension:

foreach($array as $key => $value)

这里的意思是在第一维中你只有一个带有键($key) data 和值($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
        )
)

如果遍历第二个维度,您将获得第二个维度的所有值:

If you loop over the second dimension you will get all values from the second dimension:

foreach($array["data"] as $key => $value)

表示在第二维中,您将有 3 个带有键的元素($key) 0, 1, 2 和值($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
)

有了这个,你可以遍历任何你想要的维度,无论它是数组还是对象.

And with this you can loop through any dimension which you want no matter if it is an array or object.

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

All of these 3 debug functions output the same data, just in another format or with some meta data (e.g. type, size). So here I want to show how you have to read the output of these functions to know/get to the way how to access certain data from your array/object.

输入数组:

$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' => 
  (object) array(
     'property' => 
    array (
      0 => 1,
      1 => 2,
      2 => 3,
    ),
  ),
)

如您所见,所有输出都非常相似.如果您现在想要访问值 2,您只需从您想要访问的值本身开始,然后从左上角"开始.

So as you can see all outputs are pretty similar. And if you now want to access the value 2 you can just start from the value itself, which you want to access and work your way out to the "top left".

1.我们首先看到,值 2 在一个键为 1 的数组中

1. We first see, that the value 2 is in an array with the key 1

// var_dump()
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)    // <-- value we want to access
  [2]=>
  int(3)
}

// print_r()
Array
(
    [0] => 1
    [1] => 2    // <-- value we want to access
    [2] => 3
)

// var_export()
array (
  0 => 1,
  1 => 2,    // <-- value we want to access
  2 => 3,
)

这意味着我们必须使用 [] 通过 [1] 访问值 2,因为该值具有键/索引1.

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

2.接下来我们看到,该数组被分配给了一个具有对象名称属性的属性

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

// var_dump()
object(stdClass)#1 (1) {
  ["property"]=>
  /* Array here */
}

// print_r()
stdClass Object
(
    [property] => /* Array here */
)

// var_export()
(object) array(
    'property' => 
  /* Array here */
),

这意味着我们必须使用 -> 来访问对象的属性,例如->属性.

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

所以到现在为止,我们知道必须使用->property[1].

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

3.最后我们看到,最外层是一个数组

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

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

// print_r()
Array
(
    [key] => stdClass Object
        /* Object & Array here */
)

// var_export()
array (
  'key' => 
  /* Object & Array here */
)

我们知道我们必须使用[]来访问数组元素,我们在这里看到我们必须使用[key"] 访问对象.我们现在可以将所有这些部分放在一起并编写:

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 欺骗您!

有些事情你必须知道,这样你就不会花几个小时去寻找它们.

Don't let PHP troll you!

There are a few things, which you have to know, so that you don't spend hours on it finding them.

  1. 隐藏"字符

  1. "Hidden" characters

有时您的键中有字符,您在浏览器中第一眼看不到这些字符.然后你会问自己,为什么你不能访问这个元素.这些字符可以是:制表符 (\t)、换行符 (\n)、空格或 html 标签(例如 </p>) 等

Sometimes you have characters in your keys, which you don't see on the first look in the browser. And then you're asking yourself, why you can't access the element. These characters can be: tabs (\t), new lines (\n), spaces or html tags (e.g. </p>, <b>), etc.

举个例子,如果你查看 print_r() 的输出,你会看到:

As an example if you look at the output of print_r() and you see:

Array ( [key] => HERE ) 

然后您尝试使用以下方式访问元素:

Then you are trying to access the element with:

echo $arr["key"];

但是您收到了通知:

注意:未定义索引:键

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

This is a good indication that there must be some hidden characters, since you can't access the element, even if the keys seems pretty correct.

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

The trick here is to use var_dump() + look into your source code! (Alternative: highlight_string(print_r($variable, TRUE));)

突然之间你可能会看到这样的东西:

And all of the sudden you will maybe see stuff like this:

array(1) {
    ["</b>
key"]=>
    string(4) "HERE"
}

现在您将看到,您的密钥中有一个 html 标签 + 一个换行符,这是您一开始没有看到的,因为 print_r() 和浏览器没有t 证明了这一点.

Now you will see, that your key has a html tag in it + a new line character, which you didn't saw in the first place, since print_r() and the browser didn't showed that.

所以现在如果你尝试这样做:

So now if you try to do:

echo $arr["</b>\nkey"];

你会得到你想要的输出:

You will get your desired output:

HERE

  • 如果您查看 XML,请永远不要相信 print_r()var_dump() 的输出

    您可能将 XML 文件或字符串加载到对象中,例如

    You might have an XML file or string loaded into an object, e.g.

    <?xml version="1.0" encoding="UTF-8" ?> 
    <rss> 
        <item> 
            <title attribute="xy" ab="xy">test</title> 
        </item> 
    </rss>
    

    现在如果你使用 var_dump()print_r() 你会看到:

    Now if you use var_dump() or print_r() you will see:

    SimpleXMLElement Object
    (
        [item] => SimpleXMLElement Object
        (
            [title] => test
        )
    
    )
    

    如您所见,您看不到标题的属性.所以正如我所说,当你有一个 XML 对象时,永远不要相信 var_dump()print_r() 的输出.始终使用 asXML() 查看完整XML 文件/字符串.

    So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.

    所以只需使用下面显示的方法之一:

    So just use one of the methods shown below:

    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>
    


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


    For more information see:

    一般(符号、错误)

    属性名称问题

    这篇关于如何访问数组/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆