3

I have wrote a simple algorithm to only store the first occurrence of a name in my array of artists. I am not concerned with the artist ID. The algorithm works fine but I am worried about performance. Does anybody see a simpler way to write this that would also improve performance if the $performers array was say 200 artists?

$performers = array(
   array('id' => '12','name' => 'Grouplove'),
   array('id' => '24','name' => 'Grouplove'),
   array('id' => '43','name' => 'Coldplay')
);

$tmp = array();
foreach($performers as $performer)
{
   $count = 0;
   foreach($tmp as $test)
   {
      if($performer['name'] == $test['name'])
      {
         $count++;
      }
   }
   if(!$count)
   {
      $tmp[] = $performer;
   }

}
4

3 回答 3

3

When adding them to $tmp array you can specify the key to be the name of the artist. Then you can just check if isset($tmp[$performer['name']]) is true and skip it if it already exists. That way you will avoid the inner loop. After populating the new $tmp array if the keys are the problem you can get only values with array_values($tmp).

$tmp = array();
foreach($performers as $performer) {
  if(!isset($tmp[$performer['name']]){
    $tmp[$performer['name']] = $performer;
  }
}

you will get something like:

array(
    'Grouplove' => array(
            'id' => '12',
            'name' => 'Grouplove',
     ),
    'Coldplay'  =>array(
            'id' => '43',
            'name' => 'Coldplay'
     )
);
于 2013-08-03T01:19:30.500 回答
2

Why can't you use the built-in function array unique since you aren't concerned about the artist ID?

于 2013-08-03T01:08:36.337 回答
0

If you are not concerned with the artist ID then:

$tmp = array_unique(array_map(function($value) {
                return $value["name"];
            }, $performers));

the result will be:

Array
(
    [0] => Grouplove
    [2] => Coldplay
)

Otherwise:

$tmp = array();
foreach($performers as $performer) {
    if(!in_array($performer["name"], array_map(function($value) {
                return $value["name"];
            }, $tmp))) {
        $tmp[] = $performer;
    }
}

the result will be:

Array
(
    [0] => Array
        (
            [id] => 12
            [name] => Grouplove
        )

    [1] => Array
        (
            [id] => 43
            [name] => Coldplay
        )

)
于 2013-08-03T01:32:13.963 回答