如何在PHP中向数组添加多个值

时间:2018-12-19 11:53:37

标签: php yii2

我想使用loop(foreach)创建一个新数组。

我的数组看起来像这样:

$q_list = Array(
    [0] => Array
    (
        [id] => 2
        [subject_id] => 1
        [question] => Question No One
        [recordstatus] => 1
    )
    [1] => Array
    (
        [id] => 3
        [subject_id] => 1
        [question] => Question No Two
        [recordstatus] => 1
    )
    [2] => Array
    (
        [id] => 4
        [subject_id] => 1
        [question] => Question No Three
        [recordstatus] => 1
    )
)

我已经这样做了,但是没有用:

foreach ($q_list as $key => $q) {
    $question[] = $q['question'];
    $question[] = $q['subject_id'];
}

1 个答案:

答案 0 :(得分:0)

这会将您的数组按subject_id分组。
我将subject_id用作多维数组中的键,这样它只会将问题数组添加到正确的子数组中。

foreach($q_list as $q){
    $res[$q['subject_id']][] = $q;
}

var_dump($res);

https://3v4l.org/HnlYW