我正在尝试计算数组$new_result_months
中的重复键,删除它们并使用匹配键更新$new_result_users
的值。如果我要做一个array_combine
,每个键都应匹配该值。我真的尝试过,但没有想到一个版本。
$new_result_months = array(
'Dec 2013',
'Jan 2014',
'Feb 2014',
'Mar 2014',
'Apr 2014',
'May 2014',
'Jun 2014',
'Jul 2014',
'Aug 2014',
'Sep 2014',
'Oct 2014',
'Oct 2014', // remove one duplicate key and keep unique one
'Nov 2014',
'Nov 2014', // remove one duplicate key and keep unique one
'Nov 2014', // remove one duplicate key and keep unique one
'Dec 2014'
);
$new_result_users = array(
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
0
);
预期输出
$new_result_months = array(
'Dec 2013',
'Jan 2014',
'Feb 2014',
'Mar 2014',
'Apr 2014',
'May 2014',
'Jun 2014',
'Jul 2014',
'Aug 2014',
'Sep 2014',
'Oct 2014',
'Nov 2014',
'Dec 2014'
);
$new_result_users = array(
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1, // needs to match with month oct 2014 and update it to 1
2, // needs to match with month nov 2014 and update it to 2
0
);
答案 0 :(得分:1)
首先,您使用array_count_values
计算重复值:
$aux = array_count_values($new_result_months);
新创建的数组$aux
将具有以下值:
['Dec 2013'] => 1
['Jan 2014'] => 1
['Feb 2014'] => 1
['Mar 2014'] => 1
['Apr 2014'] => 1
['May 2014'] => 1
['Jun 2014'] => 1
['Jul 2014'] => 1
['Aug 2014'] => 1
['Sep 2014'] => 1
['Oct 2014'] => 2
['Nov 2014'] => 3
['Dec 2014'] => 1
然后,使用foreach循环,您可以创建所需的新数组:
foreach($aux as $key => $value) {
$new_result_months[] = $key;
$new_result_users[] = $value;
}