7

我有一个这样的数组:

$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 循环中遍历数组,但有更好的方法吗?

4

5 回答 5

17

在 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));
于 2014-08-29T04:30:14.463 回答
15

使用 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

于 2014-08-29T04:30:22.107 回答
2

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);
于 2014-08-29T04:40:23.627 回答
0

尝试这个

$uniqueA = array_unique($a, "type");
// then to output the array just type
print_r($uniqueA);
于 2014-08-29T04:39:38.787 回答
0

您也可以使用 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');
于 2015-10-23T18:10:12.300 回答