Reputation: 375
I have an array with products where i want to search for duplicate names and increment the duplicate values.
I tried to create an empty array and push all the title values key[0] to it, then i found how many duplicates i have for each value of key[0] with array_count_values.
This is my array;
$products=Array
(
[0] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[1] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[2] => Array
(
[0] => 'Intel I3',
[1] => 250,
[2] => 'intel-i3'
),
[3] => Array
(
[0] => 'AMD graphic',
[1] => 146,
[2] => 'amd-graphic'
)
);
I want this result with incrementing by 1.
How can i get this result ?
$products=Array
(
[0] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[1] => Array
(
[0] => 'Intel I3_1',
[1] => 146,
[2] => 'intel-i3'
),
[2] => Array
(
[0] => 'Intel I3_2',
[1] => 250,
[2] => 'intel-i3'
),
[3] => Array
(
[0] => 'AMD graphic',
[1] => 146,
[2] => 'amd-graphic'
)
);
Upvotes: 0
Views: 479
Reputation: 3004
$titleCounts = array();
foreach ($products as &$product) {
if (!isset($titleCounts[$product[0]])) {
$titleCounts[$product[0]] = 0;
} else {
$titleCounts[$product[0]]++;
$product[0] = ($product[0].'_'.$titleCounts[$product[0]]);
}
}
You can see this work here:
Upvotes: 3
Reputation:
Tested, and it works.
$tmpArray = array();
foreach ($products as &$product) {
$name = $product[0];
if (array_key_exists($name, $tmpArray)) {
$product[0] = $name . '_' . $tmpArray[$name];
$tmpArray[$name]++;
} else {
$tmpArray[$name] = 1;
}
}
unset($product);
Upvotes: 0
Reputation: 11942
<?php
$counter = [];
$i = 0;
foreach($products as $product){
$counter[] = $product[2];
$vals = array_count_values($counter);
$current_number = $vals[$product[2]];
if($current_number)
$products[$i][0] .= '_'.$current_number;
$i++;
}
That should do.
Upvotes: 0