John Davidson

Keep just a certain amount of duplicate value in an array in PHP

0 comments
Message:


I have an array like this:


array
(
[0] => array(
'title' => 'pizza',
'store_id' => 65
),
[1] => array(
'title' => 'hamburger',
'store_id' => 65
),
[2] => array(
'title' => 'sandwich',
'store_id' => 65
),
[3] => array(
'title' => 'soda',
'store_id' => 65
),
[4] => array(
'title' => 'salad',
'store_id' => 50
),
)
)

I need to filter this to get only 3 items of each store. It can be the first 3 occurrences.


Any ideas to solve this?


Obs: There's a lot more items and columns in each array.



My Answer:
"apple",
[1] = "banana",
[2] = "apple",
[3] = "orange",
[4] = "banana",
[5] = "apple"
)_I want to keep only a certain amount of duplicate values in the array, for example, I want to keep only 2 duplicates of each value. So the resulting array should be:_array_(_ [0] = "apple",
[1] = "banana",
[2] = "apple",
[3] = "orange",
[4] = "banana"
)_Here's the PHP code to achieve this:php $array = array("apple", "banana", "apple", "orange", "banana", "apple");
$allowedDuplicates = 2;
$counts = array_count_values($array);
$result = array();
foreach ($array as $value) {
if ($counts[$value] > 0) {
$result[] = $value;
$counts[$value]--;
}
if ($counts[$value] >= $allowedDuplicates) {
$counts[$value] = $allowedDuplicates;
}
}
print_r($result);
?>
This code uses the `array_count_values` function to count the occurrences of each value in the array. Then, it iterates over the array and keeps only the allowed number of duplicates for each value. The resulting array is stored in the `$result` variable and printed out using `print_r`.

Rate this post

3 of 5 based on 7732 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us