Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在对象数组上使用PHP内爆_Php_Arrays - Fatal编程技术网

如何在对象数组上使用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