Home > Software design >  Remove duplicates keys in multiples arrays PHP
Remove duplicates keys in multiples arrays PHP

Time:12-03

I have an array ($datas) with subs arrays like this :

array

enter image description here

I need to remove subs arrays with same [0] value. But i can't do it.

I tested with array_unique() and many foreach in another foreach but i don't understand the methodology(correct in english?).

Any suggestion are welcome !

CodePudding user response:

Ok, i found a solution !

  $datasCounter = count($curlDatas["data"]); //datas counts

            $subArrays = array_slice($datas, 0, $datasCounter);
            foreach ($datas as $k => $v) {
                foreach ($subArrays as $key => $value) {
                    if ($k != $key && $v[0] == $value[0]) {
                        unset($subArrays[$k]);
                    }
                }
            }

CodePudding user response:

Here is a solution that uses a map. This is a very efficient solution I think for your case:

// First, create an array of sub-arrays.
$arr = [
    [1, 2, 3],
    [1, 5, 6],
    [3, 3, 4],
    [1, 7, 8]
];

// We create a 'map' in PHP, which is basically just an array but with non-sequential (non-ordered) keys.
$map = [];

// We loop through all the sub-arrays and save the pair (first element, sub-array)
// since it's a 'map', it will only keep 1.
foreach($arr as $subarr)
{
  // The 'idx' is the first element (sub-array[0])
  $first = $subarr[0];
  // If you want the first appearance of the first element (in this case [1,2,3] for '1')
  // then you check if the first element of this sub-array was already found (is in the map)
  if (!array_key_exists($first, $map))
    $map[$first] = $subarr; // Set the 
}

// Now we convert the 'map' into an array with sequential keys,
// since the 'map' is just an array with non-sequential keys.
$arr = array_values($map);

// You can print the output.
print_r($arr);

The output in this case will be:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 3
            [1] => 3
            [2] => 4
        )
)
  • Related