'PHP array duplicate add value to that index
am just trying to fix my problem. Exactly: I have array that has been filled up by database (music playlist). That array contains duplicates what am trying to achieve is (example rows from database):
-- ID: 0 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 1 |
-- ID: 1 | ARTIST: SOMETHING2 | TITLE: SOMETHING2 | TIME: 02:40 | REPEAT: 1 |
-- ID: 2 | ARTIST: SOMETHING3 | TITLE: SOMETHING3 | TIME: 03:20 | REPEAT: 1 |
-- ID: 3 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 1 |
-- ID: 4 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 1 |
-- ID: 5 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 1 |
-- ID: 6 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 1 |
So those values would be in array now how would I check for those duplicates in that array. If there would be duplicate I'd want to remove that duplicate but leave only one and add +1 to repeat for each duplicate. Example from above rows:
-- ID: 0 | ARTIST: SOMETHING1 | TITLE: SOMETHING1 | TIME: 04:00 | REPEAT: 5 |
-- ID: 1 | ARTIST: SOMETHING2 | TITLE: SOMETHING2 | TIME: 02:40 | REPEAT: 1 |
-- ID: 2 | ARTIST: SOMETHING3 | TITLE: SOMETHING3 | TIME: 03:20 | REPEAT: 1 |
Am sorry if there is already post but couldn't find way to explain it better.
Solution 1:[1]
You can use a for/foreach loop with every data you have. Then add the new data when something is not there. And put an auto increment on the ID with primary key.
Solution 2:[2]
If it has to be in PHP and not SQL, then how about:
$keys=[];
foreach($rows as $row) {
$id=$row['ARTIST'].$row['TITLE'];
if ( !isset($keys[$id]) ) $keys[$id]=$row;
else {
$rowX=$keys[$id];
$rowX['REPEAT']++;
$keys[$id]=$rowX;
}
}
See http://sandbox.onlinephpfunctions.com/code/8558cf3ae956ac358962bf3c83ecabc299a38af3 for a working example
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sohan Arafat |
| Solution 2 |
