Get unique value of one attribute from array of associative arrays

后端 未结 5 591
青春惊慌失措
青春惊慌失措 2021-01-18 06:38

I have an array like this:

$a = array(
    0 => array(\'type\' => \'bar\', \'image\' => \'a.jpg\'),
    1 => array(\'type\' => \'food\', \'ima         


        
5条回答
  •  清歌不尽
    2021-01-18 07:23

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

提交回复
热议问题