一个数组array3 0 = array5 id = int1 name = string1 1 district_name = string9 邵阳县 noise_type = int2 code = string6 430321 1 = array5 id = int2 name = string3 123 district_nam
可以使用循环遍历数组,根据code的值将对应的id添加到新的一维数组中。以下是一种实现方式:
$array = [
[
"id" => 1,
"name" => "1",
"district_name" => "邵阳县",
"noise_type" => 2,
"code" => "430321"
],
[
"id" => 2,
"name" => "123",
"district_name" => "湘潭县",
"noise_type" => 0,
"code" => "430321"
],
[
"id" => 4,
"name" => "222",
"district_name" => "开福区",
"noise_type" => 0,
"code" => "430105"
]
];
$result = [];
foreach ($array as $item) {
$code = $item['code'];
$id = $item['id'];
if (!isset($result[$code])) {
$result[$code] = [];
}
$result[$code][] = $id;
}
$result = array_values($result);
print_r($result);
输出结果为:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 4
)
)
最后使用array_values函数将关联数组转换为索引数组,即可得到最终结果。
原文地址: https://www.cveoy.top/t/topic/i6Mv 著作权归作者所有。请勿转载和采集!