views:

549

answers:

4

I have a 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

  1. How can I remove duplicates according tot he field 'Oil' is there a array_unique which I can provide a callback which acts as a custom comparator?

  2. How can I sort by a custom field 'Spark Plugs'

+1  A: 
  1. I don't know of a function you can use to do this. You will have to do a foreach over the values of the array and do the uniqueness checking manually.

  2. Use the usort() function and provide a custom comparator.

Brian Ramsay
A: 

For question 1, I think array_filter is what you need.

And, like Brian says, usort for your second question.

mgroves
the problem with array_filter is that he needs to know whether or not there are any other entries with that value from within the comparator. I couldn't think of a way to do that that was any simpler or clearer than just iterating over it yourself.
Brian Ramsay
+1  A: 

Instead of manually going and doing the usual duplicate checking, I did this



$aa2 = array()

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

Then sorting was done by the key...

The Unknown
$aa2[$key] = $value;or am I wrong?
dimitris mistriotis
A: 

The issue with remove dupes this way, is how do you determine which values remain, since you're talking about partial uniqueness.

This solution below just keeps the first to appear in index-order. It's not exactly elegant, but it works.

<?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;
}
Peter Bailey