php数组分组
$order_item = Array (
0 => Array ( 'order_id' => 1111 ,'item_id' => 1, 'pro_id' => 1, 'pro_name' => 1111 ,'buy_num' => 5),
1 => Array ( 'order_id' => 1111 ,'item_id' => 2 ,'pro_id' => 2 ,'pro_name' => 2222, 'buy_num' => 5 ),
2 => Array ( 'order_id' => 2222 ,'item_id' => 3 ,'pro_id' => 1 ,'pro_name' => 2222, 'buy_num' => 1 ),
3 => Array ( 'order_id' => 2222 ,'item_id' => 4 ,'pro_id' => 2 ,'pro_name' => 2222, 'buy_num' => 1 )
);
$ar = array();
$result = array();
foreach($order_item as $k => $v) {
$ar[$v['order_id']]['items'][] = array_slice($v, 1);
}
foreach($ar as $k => $v) $result[] = array('order_id' => $k, 'items' => $v['items']);
echo '<pre style="font:10px Tahoma;">';
print_r($result);
/*
Array
(
[0] => Array
(
[order_id] => 1111
[items] => Array
(
[0] => Array
(
[item_id] => 1
[pro_id] => 1
[pro_name] => 1111
[buy_num] => 5
)
[1] => Array
(
[item_id] => 2
[pro_id] => 2
[pro_name] => 2222
[buy_num] => 5
)
)
)
[1] => Array
(
[order_id] => 2222
[items] => Array
(
[0] => Array
(
[item_id] => 3
[pro_id] => 1
[pro_name] => 2222
[buy_num] => 1
)
[1] => Array
(
[item_id] => 4
[pro_id] => 2
[pro_name] => 2222
[buy_num] => 1
)
)
)
)
*/
不同思路的解决方案
<?php
$order_item = Array (
0 => Array ( 'order_id' => 1111 ,'item_id' => 1, 'pro_id' => 1, 'pro_name' => 1111 ,'buy_num' => 5),
1 => Array ( 'order_id' => 1111 ,'item_id' => 2 ,'pro_id' => 2 ,'pro_name' => 2222, 'buy_num' => 5 ),
2 => Array ( 'order_id' => 2222 ,'item_id' => 3 ,'pro_id' => 1 ,'pro_name' => 2222, 'buy_num' => 1 ),
3 => Array ( 'order_id' => 2222 ,'item_id' => 4 ,'pro_id' => 2 ,'pro_name' => 2222, 'buy_num' => 1 )
);
$items = array();
foreach($order_item as $item) {
$order_id = $item['order_id'];
unset($item['order_id']);
if(!isset($items[$order_id])) {
$items[$order_id] = array('order_id'=>$order_id, 'items'=>array());
}
$items[$order_id]['items'][] = $item;
}
// 下面这一步可不要
sort($items);
print_r($items);
$arr = array(
array('countyid' => 1, 'county' => '中国','province'=>'湖南'),
array('countyid' => 1, 'county' => '中国','province'=>'湖南'),
array('countyid' => 3, 'county' => '日本','province'=>'名古屋'),
array('countyid' => 3, 'county' => '日本','province'=>'东京'),
array('countyid' => 1, 'county' => '中国','province'=>'北京'),
array('countyid' => 1, 'county' => '中国','province'=>'山东'),
array('countyid' => 1, 'county' => '中国','province'=>'山东'),
array('countyid' => 2, 'county' => '美国','province'=>'安大略'),
array('countyid' => 2, 'county' => '美国','province'=>'安大略'),
array('countyid' => 3, 'county' => '日本','province'=>'名古屋'),
);
foreach($arr as $v){
$c[$v['county']]++;
$cp[$v['county'].' '.$v['province']]++;
}
var_dump($c);
var_dump($cp);
输出:
<pre>array(3) {
["中国"] => int(5)
["日本"] => int(3)
["美国"] => int(2)
}</pre><pre>array(6) {
["中国 湖南"] => int(2)
["日本 名古屋"] => int(2)
["日本 东京"] => int(1)
["中国 北京"] => int(1)
["中国 山东"] => int(2)
["美国 安大略"] => int(2)
}</pre>