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

Here is the code that will iterate over an array of classes, and push the content_id property of each element (if it exists) into an array:

# 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 );
    }
}

Is there a shorter, more declarative way to achieve this?

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);

Output:

Array
(
    [0] => y
)

This may not be much shorter but it seems a good choice for a declarative approach is to use array_reduce().

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

Two lines could be saved by using the short-circuiting logical AND operator (i.e. &&), though some would argue it is less readable.

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

See it demonstrated in this phpfiddle.