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

shi*_*.ja 6 php arrays foreach unique unique-values

我有这样一个数组:

$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')
)
Run Code Online (Sandbox Code Playgroud)

我如何计算出独特的类型值(食物,条形和默认值)?我可以在foreach循环中遍历数组但是有更好的方法吗?

koa*_*dev 12

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

$unique_types = array_unique(array_map(function($elem){return $elem['type'];}, $a));
Run Code Online (Sandbox Code Playgroud)

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

function get_type($elem)
{
    return $elem['type'];
}

$unique_types = array_unique(array_map("get_type", $a));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ler 11

使用PHP> = 5.5,您可以:

$ar = array_unique(array_column($a, 'type'));
Run Code Online (Sandbox Code Playgroud)

print_r($ar):

Array ( 
    [0] => bar 
    [1] => food 
    [3] => default 
)
Run Code Online (Sandbox Code Playgroud)

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

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

  • @true这怎么可能更"直截了当"?这看起来很简单.应该欣赏使用语言较新版本中提供的更新功能而不是混淆. (2认同)