按首字母过滤数组 [英] Filter array by first letter

查看:87
本文介绍了按首字母过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个平台.在我的代码中的某个地方,有一个看起来像这样的数组(PHP):

I'm building a platform. Somewhere in my code, there's an array that looks like this (PHP):

$entries = array('p01','p02','g01','g02','a001','a002')

我需要编写一个脚本,该脚本根据第一个字母过滤数组.例如,问那些以"p"开头的人会给我

I need to write a script that filters the array based on the first letter. For example, asking for those with the starting letter "p" would give me

$filtered_entries = array('p01','p02');

类似地,如果我要问那些以"g"或"a"开头的字母,那也会给我.知道如何实现吗?

Similarly, if I asked for those with starting letter "g" or "a" it would give me those as well. Any idea how to accomplish this?

推荐答案

PHP中有一个array_filter()函数,可用于完成此任务:

There is an array_filter() function in PHP which you can use to accomplish this:

$filtered = array_filter($array, create_function('$a', 'return $a[0] == "' . $letter . '";'));

我将留给您概括处理所有字母的功能.

请参阅: http://www.php.net/manual/zh/function.array-filter.php

这篇关于按首字母过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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