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

问题描述 投票:0回答:3

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

我只对该数组的属性之一感兴趣。我知道如何通过

foreach()
迭代数据集,但是有函数式方法吗?

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

我的课是这样的:

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")
];
php arrays object oop private-members
3个回答
5
投票

array_map
之前使用
implode

$ids = implode(",", array_map(function ($item) {
    return $item->getId();
}, $itemList));

0
投票

您已经对 getter 脚本进行了“yatta-yatta”编辑,因此我将演示两种 getter 方法的两种函数样式方法。

  1. 如果类包含显式命名的方法:(Demo)

    public function getId()
    {
        return $this->id;
    }
    

    然后你可以使用2个周期:

    echo implode(',', array_map(fn($obj) => $obj->getId(), $itemList));
    

    或带条件的 1 个周期:

    echo array_reduce(
             $itemList,
             fn($result, $obj) => $result . ($result ? ',' : '') . $obj->getId()
         );
    



  2. 如果类包含魔术方法

    __get()
    :(Demo)

    public function __get($prop)
    {
        return $this->$prop;
    }
    

    然后你可以使用2个周期:

    echo implode(',', array_map(fn($obj) => $obj->id, $itemList));
    

    或带条件的 1 个周期:

    echo array_reduce(
             $itemList,
             fn($result, $obj) => $result . ($result ? ',' : '') . $obj->id
         );
    

-3
投票

您可以简单地使用

$ids = implode(',',$itemList);

© www.soinside.com 2019 - 2024. All rights reserved.