Jump to content

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


imgrooot

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");
$get_records->execute();
$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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.