PHP合并2个数组并使用相同的值创建多维数组

时间:2017-09-11 16:22:13

标签: php arrays multidimensional-array

我有一个来自我的数据库的数组,它只包含问题和答案。我试图合并2个数组并创建多维数组,如果值多于一个。

Array
(
    [0] => Array
        (
            [question_id] => 1
            [option_id] => 1
        )

    [1] => Array
        (
            [question_id] => 2
            [option_id] => 3
        )

    [2] => Array
        (
            [question_id] => 3
            [option_id] => 5
        )

    [3] => Array
        (
            [question_id] => 3
            [option_id] => 6
        )

)

我试图将答案和问题分成2个不同的数组,但无法想出如何再次合并它们。

$user_questions = array_column($answers, 'question_id');
$user_answers = array_column($answers, 'option_id');

我需要的是(问题3有2个答案):

Array
(
    [1] => 1
    [2] => 3
    [3] => Array (5, 6)
)

2 个答案:

答案 0 :(得分:0)

您可以在从查询中获取结果时对数据进行分组,而不是在事后处理结果。为了获得你现在拥有的阵列,你现在正在做这样的事情:

while ($row = $stmt->someFetchMethod()) {
    $result[] = $row;
}

相反,使用问题id作为结果数组中的键,并将选项id附加到该键的数组中。

while ($row = $stmt->someFetchMethod()) {
    $result[$row['question_id']][] = $row['option_id'];
}

答案 1 :(得分:0)

下面的代码将通过循环现有数组来创建一个新数组。

// Considering your existing array to be like this
$array = array(
    '0' => array('question_id' => 1,'option_id' => 1),
    '1' => array('question_id' => 2, 'option_id' => 3 ),
    '2' => array('question_id' => 3,'option_id' => 5),
    '3' => array('question_id' => 3,'option_id' => 6)
);
//define new array
$new_array = array();
// loop the array
foreach($array as $key=>$value){
// if the option/answer is already set to to question key 
if(isset($new_array[$value['question_id']])){
    // if question key is an array, push new option to that array
    if(is_array($new_array[$value['question_id']])){
        array_push($new_array[$value['question_id']], $value['option_id']);
    }else{
        // convert question key to array with the old value and new option value
        $new_array[$value['question_id']] = array($new_array[$value['question_id']],$value['option_id']);
    } 
} 
else{
    // assing option as value to question key
    $new_array[$value['question_id']] = $value['option_id'];
}
}
     print_r($new_array);

Out put:

Array
(
    [1] => 1
    [2] => 3
    [3] => Array
        (
            [0] => 5
            [1] => 6
        )

)