使用子在PHP数组分组和诉诸值 [英] Grouping and resorting values in PHP array using substrings

查看:131
本文介绍了使用子在PHP数组分组和诉诸值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串值按字母排序的数组:洛杉矶加州 日本大阪; 圣迭戈,加利福尼亚州; 日本东京;等我需要输出的HTML命令和团体按字母顺序的项目由逗号后的子字符串,然后由逗号前的子字符串阿尔法。理想的情况是什么,我会得到一组嵌套的无序列表:

加利福尼亚

 洛杉矶圣地亚哥

日本

 大阪东京

任何帮助将是非常美联社preciated。谢谢你。


解决方案

  $ source_array =阵列(...); //你的数组
$ result_array =阵列();
的foreach($ source_array为$项目){
   列表($城市$州)=爆炸('',$项目);
   $状态=修剪($状态);
   $ result_array [$状态] [] = $城市;
}
//然后做一些,比如ksort
ksort($ result_array);

I have an array sorted alphabetically with string values like this: "Los Angeles, California"; "Osaka, Japan"; "San Diego, California"; "Tokyo, Japan"; etc. I need to output html that orders and groups the items alphabetically by the substring after the comma, then alpha by the substring before the comma. Ideally what I would get a set of nested unordered lists:

California

Los Angeles

San Diego

Japan

Osaka

Tokyo

Any help would be much appreciated. Thanks.

解决方案

$source_array = array(...);    // your array
$result_array = array();
foreach ($source_array as $item) {
   list($city, $state) = explode(',', $item);
   $state = trim($state);
   $result_array[$state][] = $city;
}
// then do some sort, ksort for example
ksort($result_array);

这篇关于使用子在PHP数组分组和诉诸值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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