我有一个包含产品及其categoryID的数组,有些产品属于同一类别。数组的输出低于
array (size=5)
'categoryID' =>
array (size=3)
0 => string '5' (length=1)
1 => string '2' (length=1)
2 => string '2' (length=1)
'name' =>
array (size=3)
0 => string 'HP Player' (length=9)
1 => string 'Android App' (length=11)
2 => string 'TV' (length=2)
'price' =>
array (size=3)
0 => string '600' (length=3)
1 => string '111' (length=3)
2 => string '1' (length=1)
'qty' =>
array (size=3)
0 => string '22' (length=2)
1 => string '22' (length=2)
2 => string '222' (length=3)
'exprice' =>
array (size=3)
0 => string '13200' (length=5)
1 => string '2442' (length=4)
2 => string '222' (length=3)
我想组合具有相同categoryID的产品,输出应如下所示:
array (size=2)
=> 0 array
'categoryID' =>
array
0 => string '5' (length=1)
'name' =>
array
0 => string 'HP Player' (length=9)
'price' =>
array
0 => string '600' (length=3)
'qty' =>
array
0 => string '22' (length=2)
'exprice' =>
array
0 => string '13200' (length=5)
=> 1 array
'categoryID' =>
array
0 => string '2' (length=1)
'name' =>
array
0 => string '2' (length=1)
1 => string '2' (length=1)
'price' =>
array
0 => string '111' (length=3)
1 => string '1' (length=1)
'qty' =>
array
0 => string '22' (length=2)
1 => string '222' (length=3)
'exprice' =>
array
0 => string '2442' (length=4)
1 => string '222' (length=3)
我怎么能这样做?感谢
答案 0 :(得分:3)
$arr = array (
'categoryID' =>
array (
0 => '5',
1 => '2',
2 => '2'
),
'name' =>
array (
0 => 'HP Player',
1 => 'Android App',
2 => 'TV'
),
'price' =>
array (
0 => '600',
1 => '111',
2 => '1'
),
'qty' =>
array (
0 => '22',
1 => '22',
2 => '222'
),
'exprice' =>
array (
0 => '13200',
1 => '2442',
2 => '222'
)
);
$cat_count = count(array_keys($arr['categoryID']));
$new_arr = array();
for($i=0;$i<$cat_count;$i++){
for($j=0;$j<$i;$j++){
if($arr['categoryID'][$i] == $arr['categoryID'][$j]){
$arr_key = array_search($arr['categoryID'][$i], $arr['categoryID']);
$cat_exists = 1;
}
}
if($cat_exists){
$new_arr[$arr_key]['name'][] = $arr['name'][$i];
$new_arr[$arr_key]['price'][] = $arr['price'][$i];
$new_arr[$arr_key]['qty'][] = $arr['qty'][$i];
$new_arr[$arr_key]['exprice'][] = $arr['exprice'][$i];
}else{
$new_arr[$i]['categoryID'][] = $arr['categoryID'][$i];
$new_arr[$i]['name'][] = $arr['name'][$i];
$new_arr[$i]['price'][] = $arr['price'][$i];
$new_arr[$i]['qty'][] = $arr['qty'][$i];
$new_arr[$i]['exprice'][] = $arr['exprice'][$i];
}
}
P.S :: $ arr 是输入数组&amp; $ new_arr 是输出(结果)数组!