簡體   English   中英

PHP合並2個數組並通過相同的值創建多維數組

[英]PHP merge 2 arrays and create multidimensional array by same values

我有一個來自數據庫的數組,它只是由問題和答案組成。 我正在嘗試合並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)
)

在從查詢中獲取結果時,可以像這樣對數據進行分組,而不是事后進行處理。 為了獲得您現在擁有的陣列,您目前正在執行以下操作:

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

而是將問題ID用作結果數組中的鍵,然后將選項ID附加到該鍵處的數組中。

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

下面的代碼將通過循環現有數組來創建一個新數組。

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

輸出:

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

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM