从关联数组的数组中获取一个属性的唯一值

编程入门 行业动态 更新时间:2024-10-28 04:25:27
本文介绍了从关联数组的数组中获取一个属性的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的数组:

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

更多推荐

从关联数组的数组中获取一个属性的唯一值

本文发布于:2023-10-23 04:27:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   组中   属性   唯一值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!