- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有以下数组,当我这样做时 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
email@saya.com
从数组?
最佳答案
访问 array
或 object
您如何使用两个不同的运算符。
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};
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
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;
->
.
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:
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.
//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:
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()
.
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"];
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()
输出
$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,
),
)),
)
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
\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"
}
print_r()
并且浏览器没有显示。echo $arr["</b>\nkey"];
HERE
print_r()
的输出或 var_dump()
如果你看 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>
关于php - 如何访问数组/对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680938/
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
PowerShell Web Access 允许您通过 Web 浏览器运行 PowerShell cmdlet。它显示了一个基于 Web 的控制台窗口。 有没有办法运行 cmdlet 而无需在控制台窗
我尝试在无需用户登录的情况下访问 Sharepoint 文件。 我可以通过以下任一方式获取访问 token 方法一: var client = new RestClient("https://logi
我目前正在尝试通过 Chrome 扩展程序访问 Google 服务。我的理解是,对于 JS 应用程序,Google 首选的身份验证机制是 OAuth。我的应用目前已成功通过 OAuth 向服务进行身份
假设我有纯抽象类 IHandler 和派生自它的类: class IHandler { public: virtual int process_input(char input) = 0; };
我有一个带有 ThymeLeaf 和 Dojo 的 Spring 应用程序,这给我带来了问题。当我从我的 HTML 文件中引用 CSS 文件时,它们在 Firebug 中显示为中止。但是,当我通过在地
这个问题已经有答案了: JavaScript property access: dot notation vs. brackets? (17 个回答) 已关闭 6 年前。 为什么这不起作用? func
我想将所有流量重定向到 https,只有 robot.txt 应该可以通过 http 访问。 是否可以为 robot.txt 文件创建异常(exception)? 我的 .htaccess 文件: R
我遇到了 LinkedIn OAuth2: "Unable to verify access token" 中描述的相同问题;但是,那里描述的解决方案并不能解决我的问题。 我能够成功请求访问 toke
问题 我有一个暴露给 *:8080 的 Docker 服务容器. 我无法通过 localhost:8080 访问容器. Chrome /curl无限期挂断。 但是如果我使用任何其他本地IP,我就可以访
我正在使用 Google 的 Oauth 2.0 来获取用户的 access_token,但我不知道如何将它与 imaplib 一起使用来访问收件箱。 最佳答案 下面是带有 oauth 2.0 的 I
我正在做 docker 入门指南:https://docs.docker.com/get-started/part3/#recap-and-cheat-sheet-optional docker-co
我正在尝试使用静态 IP 在 AKS 上创建一个 Web 应用程序,自然找到了一个带有 Nginx ingress controller in Azure's documentation 的解决方案。
这是我在名为 foo.js 的文件中的代码。 console.log('module.exports:', module.exports) console.log('module.id:', modu
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用 MGTwitterEngine"将 twitter 集成到我的应用程序中。它在 iOS 4.2 上运行良好。当我尝试从任何 iOS 5 设备访问 twitter 时,我遇到了身份验证 to
我试图理解访问键。我读过https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-se
我正在使用以下 API 列出我的 Facebook 好友。 https://graph.facebook.com/me/friends?access_token= ??? 我想知道访问 token 过
401 Unauthorized - Show headers - { "error": { "errors": [ { "domain": "global", "reas
我已经将我的 django 应用程序部署到 heroku 并使用 Amazon s3 存储桶存储静态文件,我发现从 s3 存储桶到 heroku 获取数据没有问题。但是,当我测试查看内容存储位置时,除
我是一名优秀的程序员,十分优秀!