Reputation: 4173
My database has 2 columns. the person's ID is repeated 5 times in 1 column and each its paired in another column with a question answer Something like this:
ID Answer
1 A1
1 A4
1 A2
1 A9
1 A3
12 A1
12 A11
12 A12
12 A17
12 A2
What i want to try to do is to merge all the answers into 1 array with its ID something like
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')
)
My code is as follows:
foreach ($quiz_answers as $aq => $aa)
{
$array_loop = array( $aa['response_id'] => array( $aa['answer'] ) );
$ss = array_merge_recursive($array_loop, $array_loop);
}
My Problem is that somehow the loop doesnt merge in the desired way and i only get 2 outputs. I am not very good at manipulating arrays and probably i need another function but i am not quite sure what i am missing. I've tried using another variable in array_merge_recursive($anotherVariable, $array_loop);
but this doesnt work either.
Upvotes: 0
Views: 1061
Reputation: 32790
$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);
Upvotes: 0
Reputation: 51950
Simply change your foreach
loop to construct the resulting array how you desire.
foreach ($quiz_answers as $aa) {
$ss[$aa['response_id']][] = $aa['answer'];
}
This gives an $ss
array as you want:
array(
1 => array('A1', 'A4', 'A2', 'A9', 'A3'),
12 => array('A1', 'A11', 'A12', 'A17', 'A2'),
)
Upvotes: 2
Reputation: 3852
echo "<pre />";
for($i=0;$i<count($array);$i++)
{
$output[$array[$i]['ID']][]=$array[$i]['Answer'];
}
print_r($output);
Upvotes: 0
Reputation: 6909
What you need to do is to have an array that holds the user ids, each of which is an associative array that holds an array of answers.
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')
)
so something like this will work (skeleton code below)
$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 );
}
Upvotes: 0