从关联数组的数组中获取一个属性的唯一值 [英] Get unique value of one attribute from array of associative arrays

查看:113
本文介绍了从关联数组的数组中获取一个属性的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

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

如何找出唯一的类型值(即食品,条形图和默认值)?我可以在foreach循环中遍历数组,但是有更好的方法吗?

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?

推荐答案

在PHP> = 5.3中,使用匿名函数:

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

这篇关于从关联数组的数组中获取一个属性的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆