Array
(
[0] => Array
(
[amount] => 8000
[date] => 2015-04-01
)
[1] => Array
(
[amount] => 5000
[date] => 2015-04-02
)
[2] => Array
(
[amount] => 5000
[date] => 2015-04-10
)
[3] => Array
(
[amount] => 25000
[date] => 2015-04-20
)
)
Array
(
[0] => Array
(
[date] => 2015-04-01
[amount] => 1000
)
[1] => Array
(
[date] => 2015-04-02
[amount] => 5000
)
[2] => Array
(
[date] => 2015-04-03
[amount] => 2000
)
[3] => Array
(
[date] => 2015-04-10
[amount] => 2000
)
)
我有两个带键和值的数组。如果'date'键值相同,则将'amount'键加起来
预期产出:
Array
(
[0] => Array
(
[date] => 2015-04-01
[amount] => 9000
)
[1] => Array
(
[date] => 2015-04-02
[amount] => 10000
)
[2] => Array
(
[date] => 2015-04-03
[amount] => 2000
)
[3] => Array
(
[date] => 2015-04-10
[amount] => 7000
)
[4] => Array
(
[date] => 2015-04-20
[amount] => 25000
)
)
答案 0 :(得分:0)
这是你的解决方案 -
<?php
$array_result = array();
$array1=array( // your first array
0 => Array
(
'amount' => 8000,
'date' => '2015-04-01'
),
1 => Array
(
'amount' => 5000,
'date' => '2015-04-02'
),
2 => Array
(
'amount' => 5000,
'date' => '2015-04-10'
),
3 => Array
(
'amount' => 25000,
'date' => '2015-04-20'
)
);
$array2=array( // your second array
0 => Array
(
'date' => '2015-04-01',
'amount' => 1000
),
1 => Array
(
'date' =>'2015-04-02',
'amount' => 5000
),
2 => Array
(
'date' => '2015-04-03',
'amount' => 2000
),
3 => Array
(
'date' => '2015-04-10',
'amount' => 2000
)
);
$array_result = $array2; // default value of result will be array2
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach( $array1 as $k1=>$val1 ) {
$is_exist = recursive_array_search($val1['date'], $array_result);
if( $is_exist !== false )
{
$array_result[ $is_exist ]['amount']+=$val1['amount'];
} else {
$array_result[]=$val1;
}
}
echo "<pre>"; print_r( $array_result );
?>