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

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

问题描述

我有以下的数组,当我做的print_r(array_values($ GET_USER)); ,我得到:

 阵列(
[0] => 10499478683521864
[1] => 1983年7月22日
[2] => email@saya.com
[3] =>艾伦[4] =>雄
[5] => Malmsteen的
[6] => https://开头万维网。 facebook.com app_scoped_user_id / 1049213468352864 /
[7] => stdClass的对象(
[ID] => 102173722491792
[名] =>印度尼西亚雅加达

〔8] => id_ID
[9] =>厄尔尼诺
[10] =>艾伦厄尔尼诺Malmsteen的
[11] =大于7
[12] => 2015-05-28T04:09:50 + 0000
[13] => 1

我试图访问数组如下:

  echo $ get_user [0]; 

但这显示了我:


未定义0

未定义0


$ b $ b

我从 Facebook SDK 4 中获取这个数组,所以我不知道原数组strucutre。



我访问作为一个例子值 email@saya.com 从数组?


解决方案

要访问数组对象,您将如何使用两个不同的运算符。



数组



要访问数组元素,你必须使用 [] 或者你没有看到这么多,但你也可以使用 {}

  echo $ array [0]; 
echo $ array {0};
//两者是等价的和可互换的



声明数组和访问数组元素



定义数组和访问数组元素是两个不同的事情。



要定义一个数组,你可以使用 array() = 5.4 [] ,并分配/设置数组/ -element。当你正在访问一个数组元素与 [] {} 如上所述,你得到一个数组的值

 // 声明数组
$ arrayA = array / b> / *这里有一些东西* / ;
$ arrayB = [ / *这里有些东西* / ] ; //仅适用于PHP> = 5.4

// 访问数组元素
echo $ array > 0 ] ;
echo $ array { 0 } ;



访问数组元素



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

 $ array [(任何表达式)] 

所以只要知道你使用什么表达式作为键以及如何由PHP解释:

 echo $ array [ 0  ]; //键是整数;它访问0的元素
echo $ array [0]; //键是 string ;它访问0的元素
echo $ array [string]; //键是 string ;它使用键'string'访问元素
echo $ array [ CONSTANT ]; //键是一个常量,它被相应的值替换
echo $ array [ cOnStAnT ]; //该键也是一个常量而不是一个字符串
echo $ array [ $ anyVariable ] //键是一个变量并且它被替换为'$ anyVariable'中的值
echo $ array [ functionXY()]; //关键是在返回值的功能



访问多维数组



如果你有多个数组在彼此,你只需要一个多维数组。要访问子数组中的数组元素,只需要使用多个 []

 回声$阵列[firstSubArray] [SecondSubArray] [ElementFromTheSecondSubArray] 
//├─────────────┘├───── ─────────────────────────
//││└────────────────────────────────────────────────────────────────────── ─第三阵列尺寸;
//│└───────────2d数组维数;
//└───────────────────第一个数组维数;



对象



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

 echo $ object   - >  

如果你在另一个对象中有一个对象,你只需要使用多个 - >

  echo $ objectA-> objectB-> property; 




注意: b
$ b


  1. 此外,如果您的属性名称无效,您必须小心!因此,要查看所有问题,您可以使用无效的属性名称查看此问题/答案。特别是这一个,如果您在资源名称的开头有数字。


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





数组&对象



现在如果你有数组和对象混合在一起,你只需要看看,如果你现在访问数组元素或对象属性,并使用相应的操作符。

 //对象
echo $ object-> anotherObject-> propertyArray [elementOneWithAnObject] - > property;
//├────┘├────────────────────────────────────────├────────── ─────────────────
//││││└──属性;
//│││└──────────────────数组元素(object);使用 - > 访问属性'property'
//││└─────────────── ───────────数组(property);使用 [] 访问数组元素'elementOneWithAnObject'
//│└─────────────── ──────────────────物(物);使用 - > 访问属性propertyArray
//└──────────────── ──────────────────────────────────────────────────────────────────────────────────使用 - > 访问属性'anotherObject'


//数组
echo $ array [arrayElement] [anotherElement] - > object-> property [element];
//├───┘├──────────┘├───────────────────────────────────────────────────────── ──────────────────
//│││││└──数组元素;
//││││└─────────property(array);使用 [] 访问数组元素'element'
//│││└──────────property(object );使用 - > 访问属性'property'
//││└─────────────── - 数组元素(对象);使用 - > 访问属性'object'
//│└──────────────── - 数组元素(数组); - 数组元素。使用 [] 访问数组元素'anotherElement'
//└──────────────── ────────────────────────────────────────────────────────────────────────────────────使用 [] 访问数组元素'arrayElement'

/ p>


  1. 如果被称为数组或对象取决于变量的最外层部分。因此, [new StdClass] 数组,即使它包含 $ object-> property = array(); 是一个对象 p>

    如果你不确定你有一个对象或数组,只需使用 gettype()





  1. 如果有人使用其他编码风格,请不要混淆: / p>

      //两种方法/样式都可以访问相同的数据
    echo $ object-> anotherObject-> propertyArray [elementOneWithAnObject] - >属性;
    echo $ object->
    anotherObject
    - > propertyArray
    [elementOneWithAnObject] - >
    property;

    //两种方法/样式都可以访问相同的数据
    echo $ array [arrayElement] [anotherElement] - > object-> property [element] ;
    echo $ array [arrayElement]
    [anotherElement] - >
    object
    - > property [element];





,Objects and Loops



如果你不只是想访问一个元素,可以遍历嵌套的数组/对象,然后遍历特定维度的值。



为此,您只需访问要循环的维度,然后就可以循环该维度的所有值。



例如,我们使用数组,但也可以是一个对象:

  Array b $ b [data] => Array(
[0] => stdClass Object(
[propertyXY] => 1

[1] =& stdClass Object(
[propertyXY] => 2

[2] => stdClass Object(
[propertyXY] => 3



如果循环第一个维度,第一维:

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

在第一维中,您只能使用键的一个元素( $ key data 和值( $ 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)

在第二维中, code> $ key 0 1 2 和值( $ 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() 输出



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



输入数组:

  $ 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()输出:

 数组

[key] => stdClass对象

[property] => Array

[0] => 1
[1 ] => 2
[2] => 3





var_export()输出:

  array(
'key'=>
stdClass :: __ set_state(array(
'property'=>
array b $ b 0 => 1,
1 => 2,
2 => 3,
),
)),

因此,您可以看到所有输出都非常相似。如果你现在想访问值2,你可以从值本身开始,你想访问它,并出发到左上角。



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

  array(3){ // var_dump )
[0] =>
int(1)
[1] =>
int(2)

[2] >
int(3)
}


$ b b

  Array  // print_r()

[0] => 1
[1] b>
[2] => 3



  array( // var_export()
0 => 1,
1 => 2,
2 => 3,
),

这意味着我们必须使用 [1] [code> [ code> ,因为值具有键/索引1。



2。接下来我们看到数组被赋值给一个具有对象的name属性的属性。

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



 stdClass 物件 // print_r()

[property] => / * Array here * /
b>



  stdClass  :: __ set_state < b>  => 
/ * Array
( array(// var_export()
'property'

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



所以到现在为止,使用 - >属性[1]



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

  array(1){ // var_dump $ b  [key]  => 
/ *此处的对象和数组* /
}



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



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

我们知道,我们必须访问一个数组元素 [] ,我们看到这里我们必须使用 [键] 以访问对象。我们现在可以把所有这些部分组合在一起,并写成:

  echo $ array [key]  - ; 

输出将是:

  2 



不要让PHP欺骗你!



有几件事情,你必须知道,所以你不要花时间去找它们。


  1. 隐藏字符



    有时候,您的键中有字符,浏览器。然后你问自己,为什么你不能访问元素。这些字符可以是:tabs( \t ),新行( \\\
    ),空格或html标记(例如< / p> < b> )等。


    例如,如果你看看 print_r()的输出,你会看到:

      Array([key] => HERE)

    然后你试图访问的元素:

      echo $ arr [key]; 

    但您收到通知:


    注意:未定义的索引:键


    这是一个很好的指示,因为你不能访问元素,即使键看起来很正确。



    这里的诀窍是使用 var_dump c $ c> +查看你的源代码! (替代方案: highlight_string(print_r($ variable,TRUE));



    可能会看到像这样的东西:

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

    你的键有一个html标签+一个新的行字符,你没有看到在第一个地方,因为 print_r()和浏览器没有显示



    现在,如果您尝试执行:

      $ arr [< / b> \\\
    key];

    您将得到所需的输出:

      HERE 


  2. c $ c> print_r() var_dump()如果你看看XML



    您可能有一个XML文件或字符串加载到对象,例如

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

    现在如果使用 var_dump() print_r()您将看到:

      SimpleXMLElement对象

    [item] => SimpleXMLElement对象

    [title] => test



    所以你可以看到你看不到标题的属性。所以我说过,当你有一个XML对象时,从不信任 var_dump() print_r()的输出。始终使用 asXML() 查看完整的XML文件/字符串。



    因此,只需使用下面显示的方法之一:

      echo $ xml-> asXML(); //查看源代码

    highlight_string($ xml-> asXML());

    header(Content-Type:text / xml);
    echo $ xml-> asXML();

    然后你会得到输出:

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







有关详情,请参阅:


$ b

常规(符号,错误)


  • 参考 - 此符号在PHP中意味着什么?

  • 参考 - 此错误在PHP中意味着什么?

  • PHP解析/语法错误;以及如何解决这些问题?



  • 属性名称问题 b


    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
            ) 
    

    I tried to access the array as followed:

    echo $get_user[0];
    

    But this displays me:

    undefined 0

    Note:

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

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

    解决方案

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

    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 {}.

    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.

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

    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.

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

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

    Note:

    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.

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

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

    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.

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

    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.

    Input array:

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

    var_dump() output:

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

    print_r() output:

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

    var_export() output:

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

    1. We first see, that the value 2 is in an array with the key 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];
    

    And the output will be:

    2
    

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


    For more information see:

    General (symbols, errors)

    Property name problems

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

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