php 如何访问数组/对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30680938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:59:15  来源:igfitidea点击:

How can I access an array/object?

phparraysclassobjectproperties

提问by Muhamad Yulianto

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

我有以下数组,当我这样做时print_r(array_values($get_user));,我得到:

Array (
          [0] => 10499478683521864
          [1] => 07/22/1983
          [2] => [email protected]
          [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
        ) 

I tried to access the array as followed:

我尝试访问数组如下:

echo $get_user[0];

But this displays me:

但这显示给我:

undefined 0

未定义 0

Note:

笔记:

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

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

How can I access as an example the value [email protected]from the array?

作为示例,我如何访问[email protected]数组中的值?

回答by Rizier123

To access an arrayor objectyou how to use two different operators.

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

Arrays

数组

To access array elements you have to use either []or which you don't see that much, but which you can also use is {}.

要访问数组元素,您必须使用其中之一,[]或者您看不到那么多,但您也可以使用 is {}

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

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.

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

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 []or {}as mentioned above you get the value of an array element opposed to setting an element.

要定义一个数组,您可以使用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:

因此,请注意您用作键的表达式以及 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

对象

To access an object property you have to use ->.

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

echo $object->property;

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

如果你在另一个对象中有一个对象,你只需要使用 multiple->来获取你的对象属性。

echo $objectA->objectB->property;

Note:

  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 oneif you have numbers at the start of the property name.

  2. You can only access properties with public visibilityfrom 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.

笔记:

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

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

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.

我希望这能让您大致了解如何访问相互嵌套的数组和对象。

Note:

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

    And if you are not sure if you have an object or array, just use gettype().

  1. 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"];
    

笔记:

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

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

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

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

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

意味着在第一维中,您将只有 1 个带有键 ( $key)data和值 ( $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)

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

在这里意味着在第二个维度你有3个元素与键($key012和值($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.

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

Analyse var_dump()/ print_r()/ var_export()output

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

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.

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

Input array:

输入数组:

$array = [
    "key" => (object) [
        "property" => [1,2,3]
    ]
];

var_dump()output:

var_dump()输出:

array(1) {
  ["key"]=>
  object(stdClass)#1 (1) {
    ["property"]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
    }
  }
}

print_r()output:

print_r()输出:

Array
(
    [key] => stdClass Object
        (
            [property] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

        )

)

var_export()output:

var_export()输出:

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

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

所以你可以看到所有的输出都非常相似。如果您现在想要访问值 2,您可以从值本身开始,您想要访问并找到“左上角”。

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

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 [1],因为该值具有键/索引 1。

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

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

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.

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

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

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

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

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

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:

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

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

And the output will be:

输出将是:

2

Don't let PHP troll you!

不要让 PHP 欺骗你!

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

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

  1. "Hidden" characters

    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.

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

    But you are getting the notice:

    Notice: Undefined index: 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.

    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"
    }
    

    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
    
  2. Never trust the output of print_r()or var_dump()if you look at 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>
    

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

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

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

    And then you will get the output:

    <?xml version="1.0" encoding="UTF-8"?>
    <rss> 
        <item> 
            <title attribute="xy" ab="xy">test</title> 
        </item> 
    </rss>
    
  1. “隐藏”字符

    有时,您的键中有字符,而您在浏览器中第一眼看不到这些字符。然后你会问自己,为什么你不能访问这个元素。这些字符可以是:制表符 ( \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
    
  2. 永远不要相信XML的输出print_r()var_dump()如果您查看 XML

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

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

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

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

    因此,如您所见,您看不到标题的属性。因此,正如我所说,永远不要相信XML 对象的输出var_dump()print_r()当您拥有 XML 对象时。始终用于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>
    


For more information see:

有关更多信息,请参阅:

General (symbols, errors)

一般(符号、错误)

Property name problems

属性名称问题

回答by splash58

From the question we can't see the structure of input array. It maybe array ('id' => 10499478683521864, 'date' => '07/22/1983'). So when you ask $demo[0] you use undefind index.

从问题我们看不到输入数组的结构。也许吧array ('id' => 10499478683521864, 'date' => '07/22/1983')。因此,当您询问 $demo[0] 时,您使用的是 undefind 索引。

Array_values lost keys and return array with numerous keys making array as array(10499478683521864, '07/22/1983'...). This result we see in the question.

Array_values 丢失了键并返回具有众多键的数组,使数组成为array(10499478683521864, '07/22/1983'...). 我们在问题中看到了这个结果。

So, you can take an array item values by the same way

因此,您可以通过相同的方式获取数组项值

echo array_values($get_user)[0]; // 10499478683521864 

回答by Evans Murithi

If your output from print_r($var)is e.g:

如果您的输出print_r($var)是例如:

    Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => [email protected] ) )

then do $var['demo'][0]

然后做 $var['demo'][0]

If the output from print_r($var)is e.g:

如果输出print_r($var)是例如:

    Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => [email protected] )

then do $var[0]

然后做 $var[0]

回答by ntheorist

I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy

我编写了一个小函数来访问数组或对象中的属性。我经常使用它,发现它非常方便

/**
 * Access array or object values easily, with default fallback
 */
if( ! function_exists('element') )
{
  function element( &$array, $key, $default = NULL )
  {
    // Check array first
    if( is_array($array) )
    {
      return isset($array[$key]) ? $array[$key] : $default;
    }

    // Object props
    if( ! is_int($key) && is_object($array) )
    {
      return property_exists($array, $key) ? $array->{$key} : $default;
    }

    // Invalid type
    return NULL;
  }
}

回答by morteza kavakebi

you can use

您可以使用

$ar = (array) $get_user;

then you can access their indices arra-wise:

然后您可以按顺序访问它们的索引:

echo $ar[0];