speedy
speedy

Reputation: 375

PHP multi dimensional array increment duplicate

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

Answers (3)

FantasticJamieBurns
FantasticJamieBurns

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:

http://ideone.com/4xoGgP

Upvotes: 3

user4299190
user4299190

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

Loïc
Loïc

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

Related Questions