Get unique value of one attribute from array of associative arrays

非 Y 不嫁゛ 提交于 2020-07-08 07:24:49

问题


I have an array like this:

$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')
)

How do I figure out unique type values (which would be food, bar and default)? I could iterate through the array in a foreach loop but is there a better way doing it?


回答1:


In PHP >= 5.3 with the use of anonymous functions:

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

For previous versions you can declare a separate function:

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

$unique_types = array_unique(array_map("get_type", $a));



回答2:


Using PHP >= 5.5, you could do:

$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




回答3:


An old fashioned way without using the fancy array_* functions. This way is simple and easy to understand. You aren't left wondering what is happening because it so straightforward.

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



回答4:


try this

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



回答5:


You could also use array_reduce.

This only doesn't work if the values of the attribute are an array or object, because those can't be set as the key of an array.

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');


来源:https://stackoverflow.com/questions/25561707/get-unique-value-of-one-attribute-from-array-of-associative-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!