如何访问数组/对象?

Muh*_*nto 58 php arrays properties class object

我有以下数组,当我这样做时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
        ) 
Run Code Online (Sandbox Code Playgroud)

我尝试按如下方式访问数组:

echo $get_user[0];
Run Code Online (Sandbox Code Playgroud)

但这显示了我:

未定义0

注意:

我从Facebook SDK 4获得这个数组,所以我不知道原来的阵列结构.

我怎样才能email@saya.com从数组中获取值作为示例?

Riz*_*123 96

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

数组

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

echo $array[0];
echo $array{0};
//Both are equivalent and interchangeable
Run Code Online (Sandbox Code Playgroud)

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

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

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

访问数组元素

到在阵列中访问特定元件可以使用任何表达内[]{},然后计算结果为要访问的键:

$array[(Any expression)]

因此,请注意您使用什么表达式作为键以及它如何被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;
Run Code Online (Sandbox Code Playgroud)

对象

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

echo $object->property;

如果在另一个对象中有一个对象,则只需使用多个->对象来获取对象属性.

echo $objectA->objectB->property;
Run Code Online (Sandbox Code Playgroud)

注意:

  1. 如果你的财产名称无效,你必须要小心!因此,要查看所有问题,您可以使用无效的属性名称来查看此问题/答案.如果您在属性名称的开头有数字,尤其是这个.

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

数组和对象

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

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

我希望这能让您大致了解如何在阵列和对象彼此嵌套时访问它们.

注意:

  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"];
    
    Run Code Online (Sandbox Code Playgroud)

数组,对象和循环

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

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

作为一个例子,我们采用一个数组,但它也可以是一个对象:

Array (
    [data] => Array (
            [0] => stdClass Object (
                    [propertyXY] => 1
                )    
            [1] => stdClass Object (
                    [propertyXY] => 2
                )   
            [2] => stdClass Object (
                    [propertyXY] => 3                   
               )    
        )
)
Run Code Online (Sandbox Code Playgroud)

如果循环遍历第一个维度,您将从第一个维度获取所有值:

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

这意味着在第一维中你只有1个元素,其中key($key)data和value($value):

Array (  //Key: array
    [0] => stdClass Object (
            [propertyXY] => 1
        )
    [1] => stdClass Object (
            [propertyXY] => 2
        )
    [2] => stdClass Object (
            [propertyXY] => 3
        )
)
Run Code Online (Sandbox Code Playgroud)

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

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

这里指在第二维度你就必须用钥匙(3元$key)0,1,2和值($value):

stdClass Object (  //Key: 0
    [propertyXY] => 1
)
stdClass Object (  //Key: 1
    [propertyXY] => 2
)
stdClass Object (  //Key: 2
    [propertyXY] => 3
)
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以遍历任何您想要的维度,无论它是数组还是对象.

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

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

输入数组:

$array = [
    "key" => (object) [
        "property" => [1,2,3]
    ]
];
Run Code Online (Sandbox Code Playgroud)

var_dump() 输出:

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

print_r() 输出:

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

        )

)
Run Code Online (Sandbox Code Playgroud)

var_export() 输出:

array (
  'key' => 
  stdClass::__set_state(array(
     'property' => 
    array (
      0 => 1,
      1 => 2,
      2 => 3,
    ),
  )),
)
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到所有输出非常相似.如果您现在想要访问值2,您可以从您想要访问的值本身开始,然后前往"左上角".

我们首先看到,值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,
),

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

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

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

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

最后我们看到,最外层是一个阵列

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

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

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

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

echo $array["key"]->property[1];
Run Code Online (Sandbox Code Playgroud)

输出将是:

2
Run Code Online (Sandbox Code Playgroud)

不要让PHP欺骗你!

有一些事情,你必须知道,这样你就不会花费数小时找到它们.

  1. "隐藏"字符

    有时你的键中有字符,在浏览器的第一眼看上去就看不到.然后你问自己,为什么你不能访问该元素.这些字符可以是:标签(\t),新线(\n),空格或HTML标签(例如</p>,<b>)等.

    作为一个例子,如果你看一下输出,print_r()你会看到:

    Array ( [key] => HERE ) 
    
    Run Code Online (Sandbox Code Playgroud)

    然后你试图访问元素:

    echo $arr["key"];
    
    Run Code Online (Sandbox Code Playgroud)

    但是你得到了通知:

    注意:未定义索引:键

    这是一个很好的指示,必须有一些隐藏的字符,因为你无法访问该元素,即使键看起来非常正确.

    这里的诀窍是使用var_dump()+查看你的源代码!(备选:highlight_string(print_r($variable, TRUE));)

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

    array(1) {
      ["</b>
    key"]=>
      string(4) "HERE"
    }
    
    Run Code Online (Sandbox Code Playgroud)

    现在您将看到,您的密钥中有一个html标记+一个新的行字符,您首先没有看到,因为print_r()浏览器没有显示.

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

    echo $arr["</b>\nkey"];
    
    Run Code Online (Sandbox Code Playgroud)

    您将获得所需的输出:

    HERE
    
    Run Code Online (Sandbox Code Playgroud)
  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>
    
    Run Code Online (Sandbox Code Playgroud)

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

    SimpleXMLElement Object
    (
        [item] => SimpleXMLElement Object
        (
            [title] => test
        )
    
    )
    
    Run Code Online (Sandbox Code Playgroud)

    所以你可以看到你没有看到标题的属性.因此,正如我说永远不要相信的输出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();
    
    Run Code Online (Sandbox Code Playgroud)

    然后你会得到输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <rss> 
        <item> 
            <title attribute="xy" ab="xy">test</title> 
        </item> 
    </rss>
    
    Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅

一般(符号,错误)

物业名称问题

  • 自 PHP 7.4 / 8 起,通过使用 {0} 调用数组键来访问数组值将被弃用,因此请不要使用它,除非您不介意将来重写代码...:) (2认同)

spl*_*h58 7

从问题我们看不到输入数组的结构.也许吧array ('id' => 10499478683521864, 'date' => '07/22/1983').所以当你问$ demo [0]时,你会使用undefind index.

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

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

echo array_values($get_user)[0]; // 10499478683521864 
Run Code Online (Sandbox Code Playgroud)