Maddie
Maddie

Reputation: 229

How to remove index from array if it has a same value

I have a multidimensional array and I would like to remove the duplicates from the index if count has same value and keep the array sorting as per provided below. Otherwise, keep the duplicates.

Here's the sample array:-

$array = (
    [0] => array(
        'count' => 3,
        'title' => 'Test title 1',
        'cost' => 300
    ),
    [1] => array(
        'count' => 3,
        'title' => 'Test title 2',
        'cost' => 200
    ),
    [2] => array(
        'count' => 2,
        'title' => 'Test title 3',
        'cost' => 600
    ),
    [3] => array(
        'count' => 2,
        'title' => 'Test title 4',
        'cost' => 500
    ),
);

From the sample array above, we should look for each index if same count value exists. If so, look for next the index and check as well if it has same value, then build a new array like the sample array below.

$newArray = (
    [0] => array(
        'count' => 3,
        'title' => 'Test title 2',
        'cost' => 200
    ),
    [1] => array(
        'count' => 2,
        'title' => 'Test title 4',
        'cost' => 500
    )
);

From the array sample above, we should check on each index if count value has no duplicates. If so, keep on building new array with the same count value.

$newArray = (
    [0] => array(
        'count' => 3,
        'title' => 'Test title 1',
        'cost' => 300
    ),
    [1] => array(
        'count' => 3,
        'title' => 'Test title 2',
        'cost' => 200
    )
);

Here's the code what I've done so far and I'm not sure with what I'm doing here:-

$newArray = [];

foreach ($array as $value) {
    if ($value['count'] == $value['count']) {
        $newArray[] = $value;
    }
    else {
        $newArray[] = $value;
    }
}

Upvotes: 1

Views: 58

Answers (1)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

This should do it:

$array = [
    ['count' => 3, 'title' => 'Test title 1', 'cost' => 300],
    ['count' => 3, 'title' => 'Test title 2', 'cost' => 200],
    ['count' => 2, 'title' => 'Test title 3', 'cost' => 600],
    ['count' => 2, 'title' => 'Test title 4', 'cost' => 500]
];

// If you want to use the first occurance
$filtered = array_reduce($array, function($acc, $item) {
    if(!in_array($item['count'], array_column($acc, 'count'))) {
        $acc[] = $item;
    }
    return $acc;
}, []);
print_r($filtered);

// Or, if you want to use the use the last occurance
$filtered = array_reduce($array, function($acc, $item) {
    $key = array_search($item['count'], array_column($acc, 'count'));
    if($key!==false) {
        $acc[$key] = $item;
    } else {
        $acc[] = $item;
    }
    return $acc;
}, []);
print_r($filtered);

Upvotes: 1

Related Questions