迭代一组类并将某些属性推送到数组中

时间:2017-04-06 15:27:14

标签: php functional-programming iteration declarative

以下代码将遍历一个类数组,并将每个元素的content_id属性(如果存在)推送到数组中:

# Collect content jobs ids from the job to process
$jobsToProcessContentIds = [];
foreach ( $jobsToProcess as $job ) {
    if ( $job->content_id ?? null ) {
        array_push( $jobsToProcessContentIds, $job->content_id );
    }
}

是否有更短,更具声明性的方法来实现这一目标?

2 个答案:

答案 0 :(得分:0)

PHP code demo

<?php
class x
{
    public $content_id="y";
}
class y
{
    public $content="z";
}
$jobsToProcess=array(new x(), new y());


$jobsToProcessContentIds=array();
foreach ($jobsToProcess as $job)
{
    if (property_exists($job, "content_id"))
    {
        $jobsToProcessContentIds[]=$job->content_id;
    }
}
print_r($jobsToProcessContentIds);

<强>输出:

Array
(
    [0] => y
)

答案 1 :(得分:0)

这可能不会短得多,但对于声明性方法来说似乎是一个很好的选择是使用array_reduce()

$jobsToProcessContentIds = array_reduce($jobsToProcess, function($carry, $job) {
    if ($job->content_id ?? null) {
        $carry[] = $job->content_id;
    }
    return $carry;
});

使用短路logical AND operator(即&&)可以保存两行,但有些人认为它不太可读。

$jobsToProcessContentIds = array_reduce($jobsToProcess, function($carry, $job) {
    ($job->content_id ?? null) && $carry[] = $job->content_id;
    return $carry;
});

this phpfiddle中看到它。