编程语言
首页 > 编程语言> > php – 数组根据索引删除重复项/保留第一次出现

php – 数组根据索引删除重复项/保留第一次出现

作者:互联网

我写了一个简单的算法,只在我的艺术家数组中存储第一个名称.我不关心艺术家ID.算法工作正常,但我担心性能.有没有人看到一个更简单的方法来写这个,如果$performers数组说200名艺术家,也会提高性能?

$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;
   }

}

解决方法:

如果您不关心艺术家ID,那么:

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

结果将是:

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

除此以外:

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

结果将是:

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

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

)

标签:php-5-3,php,performance,algorithm
来源: https://codeday.me/bug/20190831/1777328.html