假設我有一組陣列
$array = (
[0] => ( [user_id] => 100440 [len_time] => 113 [create_date] => 20190801 )
[1] => ( [user_id] => 100440 [len_time] => 55 [create_date] => 20190801 )
[2] => ( [user_id] => 100440 [len_time] => 232 [create_date] => 20190801 )
[3] => ( [user_id] => 100911 [len_time] => 299 [create_date] => 20190814 )
[4] => ( [user_id] => 101073 [len_time] => 679 [create_date] => 20190808 )
[5] => ( [user_id] => 101088 [len_time] => 3436 [create_date] => 20190806 )
[6] => ( [user_id] => 101088 [len_time] => 101073 [create_date] => 20190806 )
[7] => ( [user_id] => 101088 [len_time] => 2755 [create_date] => 20190812 )
[8] => ( [user_id] => 101088 [len_time] => 75 [create_date] => 20190814 )
[9] => ( [user_id] => 101153 [len_time] => 294 [create_date] => 20190801 )
)
我想要判斷
每個 key 'user_id', 'create_date'與
其他的 key 'user_id' , 'create_date' 相等的話
就將len_time相加
最後我想要的結果是
new_array = (
[0] => ( [user_id] => 100440 [len_time] => 400 [create_date] => 20190801 )
[1] => ( [user_id] => 100911 [len_time] => 299 [create_date] => 20190814 )
[2] => ( [user_id] => 101073 [len_time] => 679 [create_date] => 20190808 )
[3] => ( [user_id] => 101088 [len_time] => 104509 [create_date] => 20190806 )
[4] => ( [user_id] => 101088 [len_time] => 2755 [create_date] => 20190812 )
[5] => ( [user_id] => 101088 [len_time] => 75 [create_date] => 20190814 )
[6] => ( [user_id] => 101153 [len_time] => 294 [create_date] => 20190801 )
)
不知道有沒有辦法做到
我卡了有點久所以跑來發問 QQ!!
<?php
$array = [
[100440,113,20190801], [100440,55,20190801], [100440,232,20190801],
[100911,299,20190814], [101073,679,20190808], [101088,3436,20190806],
[101088,101073,20190806], [101088,2755,20190812], [101088,75,20190814],
[101153,294,20190801]
];
$array_new=[];
for($i=0;$i<count($array);$i++){
if(count($array_new)==0){
array_push($array_new,[$array[$i][0],$array[$i][1],$array[$i][2]]);
}else{
$ck=-1;
for($j=0;$j<count($array_new);$j++){
if($array[$i][0]==$array_new[$j][0]&&
$array[$i][2]==$array_new[$j][2]){
$ck=$j;
$array_new[$j][1]+=$array[$i][1];
break;
}
}
if($ck==-1){
array_push($array_new,[$array[$i][0],$array[$i][1],$array[$i][2]]);
}
}
}
echo '$array 陣列長度: '.count($array).'<hr/>';
echo '$array_new 陣列長度: '.count($array_new).'<hr/>';
var_dump($array);
echo '<hr/>';
var_dump($array_new);
?>
參考看看...
練練手 =DD
$array = array(...ry);
$_arr = array();
foreach( $array as $d ){
$_arr[ $d['user_id'].'_'.$d['create_date'] ]+=$d['len_time'];
}
$new_arr = array();
foreach( $_arr as $key => $len_time ){
list( $user_id, $create_date ) = explode('_', $key);
$new_arr[] = compact('user_id', 'len_time', 'create_date');
}
echo "<pre>",print_r($new_arr),"</pre>";