Remove duplicates / sorting from an array of associative arrays in PHP

I have an array of associative arrays

aa [] = ('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
aa [] = ('Tires' => 454, 'Oil' => 43, 'Spark Plugs' => 3);
aa [] = ('Tires' => 34, 'Oil' => 55, 'Spark Plugs' => 44);
aa [] = ('Tires' => 454, 'Oil' => 43, 'Spark Plugs' => 45);
aa [] = ('Tires' => 34, 'Oil' => 55, 'Spark Plugs' => 433);
aa [] = ('Tires' => 23, 'Oil' => 33, 'Spark Plugs' => 44);

Two questions

  • How can I remove duplicates according to the Oil field, is there an array_unique that I can provide a callback that acts like a custom comparator?

  • How can I sort by "Spark Plugs" custom field

+3
source share
5 answers
  • I do not know what function you can use for this. You will need to do foreach on the array values ​​and perform a uniqueness check manually.

  • Use usort () and provide a custom comparator.

+1
source

Instead of manually performing a normal duplicate check, I did this


$ aa2 = array ()

foeach($aa as $key => $value)  {
  $aa2[$value['Oil']] = $value;
}
$aa = $aa2;

...

+1

1, , array_filter - , .

, , .

0

, , , .

, , . , .

<?php

$aa = array();
$aa[] = array('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>3 );
$aa[] = array('Tires'=>34,  'Oil'=>55, 'Spark Plugs'=>44 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>45 );
$aa[] = array('Tires'=>34,  'Oil'=>55, 'Spark Plugs'=>433 );
$aa[] = array('Tires'=>23,  'Oil'=>33, 'Spark Plugs'=>44 );

echo '<pre>';
print_r( arrayUniqeBySubKey( $aa, 'Oil' ) );
echo '</pre>';

function arrayUniqeBySubKey( $array, $key )
{
  $indexAggregates = array();

  foreach ( $array as $idx => $subArray )
  {
    $indexAggregates[$subArray[$key]][] = $idx;
  }

  foreach ( $indexAggregates as $originalIndexes )
  {
    $numOriginals = count( $originalIndexes );
    if ( 1 == $numOriginals )
    {
      continue;
    }
    for ( $i = 1; $i < $numOriginals; $i++ )
    {
      unset( $array[$originalIndexes[$i]] );
    }
  }
  return $array;
}
0

array_filter :

$bb = array_filter($aa, function($item) {
    static $tmp = array();

    if ($filter = !in_array($item['Oil'], $tmp)) {
        $tmp[] = $item['Oil'];
    }

    return $filter;
});

This uses a static variable inside the function to "remember" the oil returned. This works because $ tmp is only used during array_filter execution. If you include this in a function and call it several times, for example, $ tmp will always be an empty array for the first call to the function provided by array_filter.

The second task, sorting, can be done using usort with a custom sorting function:

usort($bb, function($a, $b) {
    return ($a['Spark Plugs'] > $b['Spark Plugs']
            ? 1
            : -1);
});
0
source

Source: https://habr.com/ru/post/1712804/


All Articles