循环数组,仅当循环的属性发生变化时才做某事

时间:2019-09-08 19:08:59

标签: php arrays foreach

在我正在执行的foreach循环中,我正在构建一个URLS数组,我想在每个循环中将此添加到此urls数组中,然后在循环中的属性更改时使用该新数组进行操作。...例如,我正在循环一个包含URL和post_id的数据集,我想继续将URLS添加到新数组中,直到post id更改为止,此时要保存新数组(我可以执行此逻辑)并清除再次使用的新数组。

此刻,

$new_array = [];
foreach ($results as $result) {

    $new_array[] = $result->url;
    $curr_id = $result->post_id;
    if($curr_id != $result->post_id) {
        $new_array = [];
    }
}

我上面的尝试总是使我感到return false,因为$ curr_id将始终等于$ result-> post_id,但是我不知道我还能在哪里设置它来监视更改。

1 个答案:

答案 0 :(得分:0)

也许我误会了,但也许是这样:

$new_array = [];
$out=[];      // store urls here when id changes
$curr_id=-1;  // create a value you know will not be viable

foreach( $results as $result ) {
    /* will be invoked on 1st iteration and subsequent iterations when post_id changes */
    if( $curr_id != $result->post_id ) {

        /* change the var to new post_id */
        $curr_id = $result->post_id;

        /* if the array is not empty at this point, save it to output array */
        if( !empty( $new_array ) )$out[]=$new_array;

        /* create new array to store urls */
        $new_array = [];
    }

    $new_array[] = $result->url;
}