3 回答
TA贡献1871条经验 获得超8个赞
您可以首先使用array_reduce过滤较低的人口(使用国家和城市的组合作为关键字)。然后将它们炸开并使用该最小值重置数组:
foreach($arr as $k => &$ar) {
$temp = array_reduce($ar, function ($carry, $item) {
$key = $item["country"] . "###" . $item["city"];
$carry[$key] = (isset($carry[$key]) && $item["population"] > $carry[$key]) ? $carry[$key] : $item["population"];
return $carry;
}, []);
$ar = [];
foreach($temp as $k => $val) {
list($country, $city) = explode("###", $k);
$ar[] = array("country" => $country, "city" => $city, "population" => $val);
}
}
直播示例:3lv4
编辑:
您可以使用array_filter,而不是foreach循环,以避免应对:
$ar = array_filter($ar, function ($item) use ($mins) {
$key = $item["country"] . "###" . $item["city"];
return $mins[$key] == $item["population"];
});
TA贡献1946条经验 获得超3个赞
我做了两个嵌套循环,第一个嵌套子数组包含一个特定键(例如100和101)的所有内容。
接下来,我遍历数据,并保留一个包含两个级别的临时数组,第一个级别将国家作为关键,第二个级别将城市作为跟踪最低人口的关键。
完成上述操作后,我将遍历临时数组以正确的格式获取国家,城市和人口,并将其附加到新数组中。然后,我用以前的数组替换这个新获取的结果。
<?php
$arr = array
(
"100" => array(
array(
"country" => 'France',
"city" => 'Paris',
"population" => '1800000',
),
array(
"country" => 'France',
"city" => 'Paris',
"population" => '2000000',
),
array(
"country" => 'France',
"city" => 'Toulouse',
"population" => '500000',
),
),
"101" => array(
array(
"country" => 'Russia',
"city" => 'Moscow',
"population" => '144000000',
)
)
);
foreach($arr as $key=>$subarr) {
$tmp = array();
foreach($subarr as $v) {
$country = $v['country'];
$city = $v['city'];
$population = $v['population'];
if(isset($tmp[$country])) {
if(isset($tmp[$country][$city])) {
if($tmp[$country][$city] > $population) {
$tmp[$country][$city] = $population;
}
} else {
$tmp[$country][$city] = $population;
}
} else {
$tmp[$country] = array();
$tmp[$country][$city] = $population;
}
}
$res = array();
foreach($tmp as $country=>$cities) {
foreach($cities as $city=>$population) {
$res[] = array('country'=>$country,'city'=>$city,'population'=>$population);
}
}
$arr[$key] = $res;
}
print_r($arr);
- 3 回答
- 0 关注
- 135 浏览
添加回答
举报