gpt4 book ai didi

php - 如何从数组中的每个对象获取对象属性?

转载 作者:可可西里 更新时间:2023-10-31 22:11:27 24 4
gpt4 key购买 nike

假设我在 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) 我可以手动循环,但我觉得一定有更好的方法。

刚看到this in the similar questions但是关于接受的答案是否真的是最好的方法存在一些争论,而且它是 2 年前的。我使用的是 PHP 5.3。

最佳答案

您可以使用 array_map从每个元素中获取 ID。

function getID($a){
return $a->id;
}
$IDs = array_map('getID', $array);

演示:http://ideone.com/nf3ug

关于php - 如何从数组中的每个对象获取对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462150/

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