从关联数组的数组中获取一个属性的唯一值


Get unique value of one attribute from array of associative arrays

我有一个这样的数组:

$a = array(
    0 => array('type' => 'bar', 'image' => 'a.jpg'),
    1 => array('type' => 'food', 'image' => 'b.jpg'),
    2 => array('type' => 'bar', 'image' => 'c.jpg'),
    3 => array('type' => 'default', 'image' => 'd.jpg'),
    4 => array('type' => 'food', 'image' => 'e.jpg'),
    5 => array('type' => 'food', 'image' => 'f.jpg'),
    6 => array('type' => 'food', 'image' => 'h.jpg')
)

如何计算出唯一的类型值(可以是食物、酒吧和默认值)?我可以在foreach循环中迭代数组,但有更好的方法吗?

在PHP>=5.3中使用匿名函数:

$unique_types = array_unique(array_map(function($elem){return $elem['type'];}, $a));

对于以前的版本,您可以声明一个单独的函数:

function get_type($elem)
{
    return $elem['type'];
}
$unique_types = array_unique(array_map("get_type", $a));

使用PHP>=5.5,您可以执行:

$ar = array_unique(array_column($a, 'type'));

print_r($ar):

Array ( 
    [0] => bar 
    [1] => food 
    [3] => default 
)

http://php.net/manual/en/function.array-column.php

http://php.net/manual/en/function.array-unique.php

不使用花哨的array_*函数的老式方式。这种方法简单易懂。你不会想知道发生了什么,因为事情太简单了。

$a = array(
    0 => array('type' => 'bar', 'image' => 'a.jpg'),
    1 => array('type' => 'food', 'image' => 'b.jpg'),
    2 => array('type' => 'bar', 'image' => 'c.jpg'),
    3 => array('type' => 'default', 'image' => 'd.jpg'),
    4 => array('type' => 'food', 'image' => 'e.jpg'),
    5 => array('type' => 'food', 'image' => 'f.jpg'),
    6 => array('type' => 'food', 'image' => 'h.jpg')
);
$types = array();
foreach($a as $key => $type) {
        if(! isset($types[$type['type']]))
                $types[$type['type']] = $type['type'];
}
var_dump($types);

尝试这个

$uniqueA = array_unique($a, "type");
// then to output the array just type
print_r($uniqueA);

您也可以使用array_reduce。

只有当属性的值是数组或对象时,这才不起作用,因为这些值不能设置为数组的键。

function array_unique_attr($arr, $key) {
    return array_keys( array_reduce($arr, function($newArr, $event) {
        $newArr[$key] = true;
        return $newArr;
    }, []) );
}
$unique_types = array_unique_attr($a, 'type');