Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique value of one attribute from array of associative arrays

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?

like image 266
shikhar.ja Avatar asked Aug 29 '14 04:08

shikhar.ja


3 Answers

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));
like image 82
omma2289 Avatar answered Oct 03 '22 02:10

omma2289


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

like image 45
Mark Miller Avatar answered Oct 03 '22 00:10

Mark Miller


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);
like image 23
Ryan Avatar answered Oct 03 '22 00:10

Ryan