从对象数组中内爆私有值列

Pau*_*llo 4 php arrays oop object private-members

我有一个对象数组,我想从每个对象中内爆特定的私有属性以形成一个分隔字符串。

我只对该数组的属性之一感兴趣。我知道如何通过迭代数据集,foreach()但是有函数式方法吗?

$ids = "";
foreach ($itemList as $item) {
    $ids = $ids.$item->getId() . ",";
}
// $ids = "1,2,3,4"; <- this already returns the correct result
Run Code Online (Sandbox Code Playgroud)

我的班级是这样的:

class Item {
    private $id;
    private $name;

    function __construct($id, $name) {
        $this->id=$id;
        $this->name=$name;
    }
    
    //function getters.....
}
Run Code Online (Sandbox Code Playgroud)

样本数据:

$itemList = [
    new Item(1, "Item 1"),
    new Item(2, "Item 2"),
    new Item(3, "Item 3"),
    new Item(4, "Item 4")
];
Run Code Online (Sandbox Code Playgroud)

Hal*_*yon 6

array_map在您之前使用implode

$ids = implode(",", array_map(function ($item) {
    return $item->getId();
}, $itemList));
Run Code Online (Sandbox Code Playgroud)