如何从数组中的每个对象获取对象属性?
假设我在 PHP 中有一个对象数组,例如:
Array (
[0] => stdClass Object (
[id] => 1
[name] => Title One
)
[1] => stdClass Object (
[id] => 2
[name] => Title Two
)
[2] => stdClass Object (
[id] => 7
[name] => Title Seven
)
)
获取 ID 数组的最佳方法(即最快)是什么?即 array(1,2,7)
我可以手动循环,但我觉得必须有更好的方法。
刚刚在类似的问题中看到了这个但是有一个关于所接受的答案是否真的是最好的方法几乎没有争议,而且它是两年前的。我使用的是 PHP 5.3。
Assuming I have an array of objects in PHP, something like:
Array (
[0] => stdClass Object (
[id] => 1
[name] => Title One
)
[1] => stdClass Object (
[id] => 2
[name] => Title Two
)
[2] => stdClass Object (
[id] => 7
[name] => Title Seven
)
)
What is the best way (i.e. fastest) to get an array of the IDs? i.e. array(1,2,7)
I can loop manually but I feel there must be a better method.
Just saw this in the similar questions but there's a little debate over whether the accepted answer is really the best way, plus it's from 2 years ago. I'm on PHP 5.3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
array_map
获取每个元素的 ID。演示:http://ideone.com/nf3ug
You can use
array_map
to get the IDs from each element.Demo: http://ideone.com/nf3ug
从 PHP 7.0 开始,您可以使用内置函数
array_column
来实现此目的,它接受一个输入数组和您想要提取的属性的名称:作为第三个参数,您可以选择提供一个索引键作为好吧:
请注意,虽然它已经在 PHP 5.5.0 中提供,但对对象数组的支持是在 PHP 7.0 中首次引入的。
Since PHP 7.0 you may use the builtin function
array_column
for that, which takes an input array and the name of the property you want to pluck:As a third parameter, you may optionally supply an index-key as well:
Please note that, although it's already available in PHP 5.5.0, support for an array of objects was first introduced in PHP 7.0.
最快的方法就是简单地循环(
foreach
、for
、while
)。使用回调函数会产生不必要的开销。我想看看是否有一种方法可以通过构建初始对象数组的代码来创建列表。
The fastest way is simply looping (
foreach
,for
,while
). Using callback functions will incur unnecessary overhead.I would look to see if there's a way to create the list via the code that is building the initial array of objects.
我正在使用 RedBean,由于某种原因传递“getID”对我来说不起作用,所以我是这样做的:
I'm using RedBean and for some reason passing in "getID" didn't work for me, so here is how I done it:
您可以使用 ouzo goodies
或使用数组(来自 ouzo goodies)
轻松完成此操作,请查看:http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
另请参阅使用 ouzo 进行函数式编程(我无法发布链接)。
You can do it easily with ouzo goodies
or with Arrays (from ouzo goodies)
Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).
您是否尝试过 array_keys 函数?
编辑:
Did you try the array_keys function?
EDIT:
您还可以使用 extract_property() 这是一个专门为此工作设计的经过良好测试的库(免责声明:我是作者)。
You can also use extract_property() which is a well tested library designed specifically for this job (disclaimer: I am the author).