簡體   English   中英

使用array_merge_recursive合並2個數組不能正常工作

[英]Merging 2 arrays using array_merge_recursive not working properly

我的數據庫有2列。 此人的ID在1列中重復5次,每次在另一列中配對並回答問題答案:

ID  Answer
1   A1
1   A4
1   A2
1   A9
1   A3
12  A1
12  A11
12  A12
12  A17
12  A2

我想要嘗試做的是將所有答案合並為1個數組,其ID類似於

array (
        [1] => array ( 0 => 'A1', 1 => 'A4', 2 => 'A2', 3 => 'A9', 4 => 'A3'),
        [12] => array ( 0 => 'A1', 1 => 'A11', 2 => 'A12', 3 => 'A17', 4 => 'A2')
        )

我的代碼如下:

foreach ($quiz_answers as $aq => $aa)
            {
                $array_loop = array(  $aa['response_id'] => array( $aa['answer'] ) );
                $ss = array_merge_recursive($array_loop, $array_loop);

            }

我的問題是,循環不會以所需的方式合並,我只得到2個輸出。 我不是很擅長操縱數組,可能我需要另一個功能,但我不太確定我缺少什么。 我嘗試在array_merge_recursive($anotherVariable, $array_loop);使用另一個變量array_merge_recursive($anotherVariable, $array_loop); 但這也不起作用。

只需更改foreach循環,即可根據需要構建生成的數組。

foreach ($quiz_answers as $aa) {
    $ss[$aa['response_id']][] = $aa['answer'];
}

這可以根據需要提供$ss數組:

array(
    1  => array('A1', 'A4', 'A2', 'A9', 'A3'),
    12 => array('A1', 'A11', 'A12', 'A17', 'A2'),
)

你需要做的是擁有一個包含用戶id的數組,每個數組都是一個包含一組答案的關聯數組。

array (
        [1] => array ( 0 => 'A1', 0 => 'A4', 0 => 'A2', 0 => 'A9', 0 => 'A3'),
        [12] => array ( 0 => 'A1', 0 => 'A11', 0 => 'A12', 0 => 'A17', 0 => 'A2')
        )

所以這樣的東西會工作(下面的骨架代碼)

$answers = array();
foreach( $quiz_answers as $id => $ans ) {
  // check if $answers[$id] exists, otherwise create it here....
  if(exists(....)) ...
  else $answers[$id] = array();

  // Then add the current answer to it, as below
  array_push($answers[$id], $ans );
}
echo "<pre />";
for($i=0;$i<count($array);$i++)
{
    $output[$array[$i]['ID']][]=$array[$i]['Answer'];
}
print_r($output);
$quiz_answers = // get all the data from database.
$res          = array();
foreach($quiz_answers as $key=>$val){
     $res[$val['response_id']][]    = $val['answer'];
}

print_r($res);

暫無
暫無

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

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