Get unique value of one attribute from array of associative arrays

后端 未结 5 652
青春惊慌失措
青春惊慌失措 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:35

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

提交回复
热议问题