在php中访问不带方括号的数组值
在 php 中,如何在不使用方括号将键括起来的情况下访问数组的值?我的特殊问题是我想访问函数返回的数组的元素。假设 function(args) 返回一个数组。为什么是 $var = 函数(args)[0]; 为方括号对我大喊大叫?我可以做类似的事情吗 $var = 函数(args).value(0); 或者我错过了一些非常基本的东西?
In php how can I access an array's values without using square brackets around the key? My particular problem is that I want to access the elements of an array returned by a function. Say function(args) returns an array. Why is
$var = function(args)[0];
yelling at me about the square brackets? Can I do something like
$var = function(args).value(0);
or am I missing something very basic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他人所说,您几乎必须使用临时变量:
但是,如果知道返回的数组的结构,则可以避免使用临时变量。
如果您只想要第一个成员:
如果您想要最后一个成员:
如果您想要中间的任何一个成员:
As the others have said, you pretty much have to use a temporary variable:
But, if know the structure of the array being returned it is possible to avoid the temporary variable.
If you just want the first member:
If you want the last member:
If you want any one in between:
在 PHP 中,当获取数组作为函数结果时,不幸的是,您必须执行额外的步骤:
对于对象,这在 PHP 5 中已放宽。您可以这样做:(
假设
function
返回一个对象课程。)In PHP, when getting an array as a function result, you unfortunately have to do an extra step:
For objects, this has been relaxed in PHP 5. You can do:
(provided
function
returns an object of course.)不幸的是,如果不添加用户功能,就无法做到这一点。它只是不是语法的一部分。
你总是可以用老式的方式来做
There is no way to do this without adding a user function unfortunately. It is just not part of the syntax.
You could always just do it the old fashion way
与您的期望完全相符的是:
台北 Kinetix Kin 的回答
What exactly matches your expecting is:
answered Kinetix Kin, Taipei
如果你想要这个,最好返回一个对象(不幸的是,它完全蹩脚的 php 不支持这个)。这是我能够弄清楚的一种疯狂的方式,出于新颖性(请不要这样做!):
所以是的..直到他们在 php 中添加对数组取消引用的支持,我认为你应该将返回数组转换为对象:
然后你可以执行 returnsArray()->foo ,因为 php 放宽了对象的解引用,但不是数组的解引用。或者当然可以像其他人建议的那样编写一个包装函数。
if you want this, its probably best to be returning an object (unfortunately, its totally lame php doesnt support this). Heres a crazy way i was able to figure out though, out of novelty (please dont do this!):
So yeah..until they add support for array dereferencing in php, i think you should probably just cast the return array as an object:
and then you can do returnsArray()->foo, since php relaxes dereferencing for objects but not arrays.. or of course write a wrapper function like others have suggested.