斯蒂芬大帝
一个数组不可能存在两个相同的key的,所有改成二维数组,相信你从数据库查出来也是二维数组
<?php
$provinces = [
[
'id' => 1,
'pinyin' => 'hunan',
'name' => '湖南',
],
[
'id' => 2,
'pinyin' => 'hubei',
'name' => '湖北',
],
[
'id' => 3,
'pinyin' => 'shanxi',
'name' => '山西',
],
[
'id' => 4,
'pinyin' => 'shanxi',
'name' => '陕西',
],
];
// 按拼音分组
$groupProvinces = [];
foreach ($provinces as $key => $value) {
$groupProvinces[$value['pinyin']][] = $value;
}
// 获取重复的的拼音
$repeats = [];
foreach ($groupProvinces as $key => $value) {
if (count($value) > 1) {
$repeats[$key] = $value;
}
}
echo '<pre>';
echo print_r($repeats);
输出的结果为:
Array
(
[shanxi] => Array
(
[0] => Array
(
[id] => 3
[pinyin] => shanxi
[name] => 山西
)
[1] => Array
(
[id] => 4
[pinyin] => shanxi
[name] => 陕西
)
)
)