这就是我到目前为止所拥有的:
foreach ($users as $user) {
if (!array_keys($usersPerCity, $user->city)) {
$usersPerCity[] = [$user->city => 1];
} else {
$usersPerCity[$user->city] = ($usersPerCity[$user->city] + 1);
}
}
我的+1没有任何效果,它只是简单地创建了city => 1,没有添加。
我怎样才能增加已经存在的城市?
你已经在
else
中做对了,只需以同样的方式进行即可。 另外,这不是 array_keys
的用途,您是说 array_key_exists
吗? 无论如何,只需使用 isset
,您就可以增加 ++
:
foreach ($users as $user) {
if (!isset($usersPerCity[$user->city])){
$usersPerCity[$user->city] = 1;
} else {
//$usersPerCity[$user->city] = ($usersPerCity[$user->city] + 1);
$usersPerCity[$user->city]++;
}
}
从 PHP 7.0 开始,只需从对象数组中提取
city
并计算值:
$usersPerCity = array_count_values(array_column($users, 'city'));
还有其他几种方法:
仅初始化 - 无需其他:
foreach ($users as $user) {
$incrementBy = 5;
if (!isset($usersPerCity[$user->city])) {
$usersPerCity[$user->city] = 0;
}
$usersPerCity[$user->city] += $incrementBy;
}
用三元让你的朋友感到惊讶和困惑:
foreach ($users as $user) {
$incrementBy = 5;
$usersPerCity[$user->city] =
(
isset($usersPerCity[$user->city])
? $usersPerCity[$user->city] + $incrementBy
: $incrementBy
)
}