我写了一个简单的算法,只在我的艺术家数组中存储第一个名称。我不关心艺术家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;
}
}
答案 0 :(得分:3)
将它们添加到$tmp
数组时,您可以指定要作为艺术家名称的键。然后你可以检查isset($tmp[$performer['name']])
是否为真,如果它已经存在则跳过它。这样你就可以避免内循环。填充新的$tmp
数组后,如果键出现问题,则只能获得array_values($tmp)
的值。
$tmp = array();
foreach($performers as $performer) {
if(!isset($tmp[$performer['name']]){
$tmp[$performer['name']] = $performer;
}
}
你会得到类似的东西:
array(
'Grouplove' => array(
'id' => '12',
'name' => 'Grouplove',
),
'Coldplay' =>array(
'id' => '43',
'name' => 'Coldplay'
)
);
答案 1 :(得分:2)
为什么不能使用内置函数array unique,因为您不关心艺术家ID?
答案 2 :(得分:0)
如果您不关心艺术家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
)
)