To remove rows that have a duplicate value in one key of an associative array in PHP, you can use the following steps:
- Loop through each element of the array and keep track of the unique values using another array.
- Create a new array to store the elements without duplicates.
- Check if the current value already exists in the unique value array. If it does, skip the current element and move to the next one.
- If the value is not already in the unique value array, add it to the array and add the current element to the new array.
- After looping through all the elements, the new array will contain only the unique elements.
Here's an example code snippet that demonstrates this process:
<?php
function removeDuplicates($array, $key) {
$uniqueValues = [];
$newArray = [];
foreach ($array as $element) {
if (!in_array($element[$key], $uniqueValues)) {
$uniqueValues[] = $element[$key];
$newArray[] = $element;
}
}
return $newArray;
}
// Example usage:
$students = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 1, 'name' => 'John'], // Duplicate row
['id' => 3, 'name' => 'Alice'],
];
$studentsWithoutDuplicates = removeDuplicates($students, 'id');
print_r($studentsWithoutDuplicates);
?>
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => John
)
[1] => Array
(
[id] => 2
[name] => Jane
)
[2] => Array
(
[id] => 3
[name] => Alice
)
)
In this example, the function removeDuplicates takes in an array and a key. It checks if the value of the specified key already exists in the $uniqueValues array. If it does not exist, it adds the value to the $uniqueValues array and adds the element to the $newArray. Finally, it returns the $newArray which contains only the unique elements based on the specified key.