Jump to content

How would you combine multiple variables of same id from a foreach loop, into a single variable?


Recommended Posts

Say I have the following.

record_id    |    record_name
1                  one
2                  two
3                  three
3                  three
3                  three
4                  four
5                  five
5                  five     

I want to search through through the table and find all the records. If there are multiple records with same id, I want to combine them into 1 variable and use that. So in the above example, I have 3 threes and 2 fives. I want to combine them so that I only get 1 three and 1 five.  How can that be done?


A normal query looks like this. 

$get_records = $db->prepare("SELECT * FROM records");
$result_records = $get_records->fetchAll(PDO::FETCH_ASSOC);
if(count($result_records) > 0) {
  foreach($result_records as $row) {
    $record_id  	= $row['record_id'];
    $record_name  	= $row['record_name'];
Link to comment
Share on other sites

If you have duplicate records in the table then you should fix that so you don't have duplicate records.


If you don't then that means each row is different, so there's a good chance that you need to be taking into consideration how each is different. If you really only care about the ID and name then

SELECT DISTINCT record_id, record_name FROM records
But based on the name "record_id" I would expect there is only one row per table with a given value, which goes back to the first thing I said.
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.