$arr1=array(
"0"=>array(
'id' => '2',
'b' => 0,
'num' => 4
),
"1"=>array(
'id' => '1',
'b' => 0,
'num' => 4
)
);
$arr2=array(
"1"=>array(
'id' => '3',
'b' => 0,
'num' => 4
),
"2"=>array(
'id' => '2',
'b' => 0,
'num' => 4
)
);
想要合並這個兩個數組,判斷條件,id,b兩個元素都相同的情況的NUM值相加。新數組鍵值重新排列0 1 2 3
求高手指點。謝謝。
<?php
$arr1=array(
"0"=>array(
'id' => '2',
'b' => 0,
'num' => 4
),
"1"=>array(
'id' => '1',
'b' => 0,
'num' => 4
)
);
$arr2=array(
"1"=>array(
'id' => '3',
'b' => 0,
'num' => 4
),
"2"=>array(
'id' => '2',
'b' => 0,
'num' => 4
)
);
$arr3 = array_merge($arr1, $arr2);
function arr_combine($array){//按照id值進行冒泡排序
$length = count($array);
for($i = 0; $i < $length; $i++) {
for($j = $i+1; $j < $length; $j++){
if ($array[$i]['id'] > $array[$j]['id'] ) {
$tmp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tmp;
}else if($array[$i]['id'] == $array[$j]['id'] && $array[$i]['b'] == $array[$j]['b']){//按照id,b值是否相同,進行合並
$array[$i]['num'] = $array[$i]['num']+$array[$j]['num'];
$array[$j]['num'] = 0;//此處將合並過的數組的num設置為0
}
}
}
//對結果數組進行處理,如果num為0,則剔除
foreach( $array as $key => $value ) {
if($value['num'] == 0) unset($array[$key]);
}
return $array;
}
var_dump(arr_combine($arr3));