如何在对象数组上使用PHP内爆
我有一个数组的对象,我想内爆。我只对该数组的一个属性感兴趣。有没有一种更简单的方法可以做到这一点,而不必遍历集合如何在对象数组上使用PHP内爆,php,arrays,Php,Arrays,我有一个数组的对象,我想内爆。我只对该数组的一个属性感兴趣。有没有一种更简单的方法可以做到这一点,而不必遍历集合 class Item { private $id; private $name; function __construct($id, $name) { $this->id=$id; $this->name=$name; } //function getters..... } $itemList=
class Item {
private $id;
private $name;
function __construct($id, $name) {
$this->id=$id;
$this->name=$name;
}
//function getters.....
}
$itemList=[new Item(1, "Item 1"), new Item(2, "Item 2"), new Item(3, "Item 3"), new Item(4, "Item 4")];
我想将$itemList($id)返回到一个逗号分隔的id字符串,即1,2,3,4,5。我知道我可以做到这一点
$ids="";
foreach($itemList as $item){
$ids=$ids.$item->getId().",";
}
我相信一定有一种更便宜的方法可以达到同样的效果 您可以简单地使用
$ids=infrade(',',$itemList)代码>在内爆之前使用数组映射
:
$ids = implode(",", array_map(function ($item) {
return $item->getId();
}, $itemList);
也就是说,如果uuu-toString返回$id,uuu-toString返回一个不同的东西,你真的需要“更便宜”,而不是清晰、明显的代码吗?如果不是,那就直接循环。当我说“便宜”时,我指的是资源友好型。可能最昂贵的资源是你和未来的维护人员。让代码尽可能简单易读,如果你发现你需要优化,当你完成基准测试并确定问题区域后,你可以随时回来。复制了,谢谢@Ken