gpt4 book ai didi

php - 如何访问数组/对象?

转载 作者:IT老高 更新时间:2023-10-28 12:06:24 25 4
gpt4 key购买 nike

我有以下数组,当我这样做时 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];

但这显示给我:

undefined 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 elementecho $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 elementecho $array["0"];          //The key is a string; It accesses the 0's elementecho $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 valueecho $array[cOnStAnT];     //The key is also a constant and not a stringecho $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;

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.



数组和对象

现在,如果数组和对象相互混合,则只需查看现在是否访问数组元素或对象属性并使用相应的运算符。
//Objectecho $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'//Arrayecho $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
)
)
)

如果您遍历第一个维度,您将获得第一个维度的所有值:
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"];

    但是您收到通知:

    Notice: Undefined index: key



    这是一个很好的迹象,表明必须有一些隐藏的字符,因为您无法访问该元素,即使键看起来非常正确。

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

    突然之间你可能会看到这样的东西:
    array(1) {
    ["</b>
    key"]=>
    string(4) "HERE"
    }

    现在您将看到,您的 key 中有一个 html 标签 + 一个换行符,这是您最初没有看到的,因为 print_r()并且浏览器没有显示。

    所以现在如果你尝试这样做:
    echo $arr["</b>\nkey"];

    您将获得所需的输出:
    HERE
  • 永远不要相信 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()print_r()你会看到:
    SimpleXMLElement Object
    (
    [item] => SimpleXMLElement Object
    (
    [title] => test
    )

    )

    因此,如您所见,您看不到标题的属性。所以正如我所说,永远不要相信 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>


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

    一般(符号、错误)
  • 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?
  • 关于php - 如何访问数组/对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680938/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com