2

I have a database with the following information:

    | ID | Name | Number |
    +----+------+--------+ 
    | 1  |  aaa |   1    |
    | 2  |  bbb |   1    |
    | 3  |  ccc |   2    |
    | 4  |  ddd |   2    |

and so on.....

What I want is to make an array like this:

    $array[1] = array ('aaa','bbb');
    $array[2] = array ('ccc','ddd');

And so on......

How do I achieve that, with a loop?

This is what I got so far:

while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']] = array ($array['Name']);
}
print_r($final_array);

This isn't working. I think I should use array_merge but can't figure out how to

4 Answers 4

3

What about:

while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']][] = $array['Name'];
}
Sign up to request clarification or add additional context in comments.

Comments

1

If $array is really an array an contains the keys ID,Number and Name

   $final_array = array();
   while ($array = $query_res->fetch_assoc()) {
       $final_array[$array['Number']][] = array ($array['Name']);
   }

and then print_r ....

Comments

0

Change your query to

SELECT `Number`, GROUP_CONCAT(DISTINCT(`Name`)) as `Name` FROM `table`

You will get a response like:

Number=1, Name=aaa,bbb Number=2, Name=ccc,ddd

Then do something like

while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']] = explode(',' $array['Name']);
}
print_r($final_array);

Comments

0

You need to check if an element with the key exists, if yes, push the new value into the array, if not create a new array:

while ($array = $query_res->fetch_assoc()) {
     if(isset($final_array[$array['Number']]){
         $final_array[$array['Number']][] = $array['Name'];
     }else{
         $final_array[$array['Number']] = array ($array['Name']);
     }
}
print_r($final_array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.