gpt4 book ai didi

php - php数组中的未定义索引

转载 作者:可可西里 更新时间:2023-11-01 00:21:38 24 4
gpt4 key购买 nike

希望获得多维数组中特定键=>值的计数。我所做的工作即结果是正确的,但我似乎无法摆脱 Undefined Index 通知。

$total_arr = array();

foreach($data['user'] as $ar) {
$total_arr[$ar['city']]++;
}

print_r($total_arr);

有什么想法吗?我已经在 foreach 循环中尝试了 isset,但没有任何乐趣......

最佳答案

$total_arr = array();

foreach($data['user'] as $ar) {
if(array_key_exists($ar['city'],$total_arr) {
$total_arr[$ar['city']]++;
} else {
$total_arr[$ar['city']] = 1; // Or 0 if you would like to start from 0
}
}

print_r($total_arr);

关于php - php数组中的未定义索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com