我有一个数组,但我想从那个数组生成其他数组..
Array
(
[0] => Array
(
[supplier] => Billy
[total_bookings] => 5
[year] => 2016
[month] => 6
[user_id] => 4
[sales_revenue] => 1180
[net_revenue] => 1180
)
[1] => Array
(
[supplier] => XYZ1
[total_bookings] => 3
[year] => 2016
[month] => 6
[user_id] => 2
[sales_revenue] => 642
[net_revenue] => 642
)
[2] => Array
(
[supplier] => Billy
[total_bookings] => 1
[year] => 2016
[month] => 3
[user_id] => 4
[sales_revenue] => 30
[net_revenue] => 30
)
[3] => Array
(
[supplier] => Billy
[total_bookings] => 1
[year] => 2015
[month] => 10
[user_id] => 4
[sales_revenue] => 30
[net_revenue] => 30
)
)
到新阵列:
Array
(
[2016] => Array(
[6] => Array
(
[0] => Array(
[supplier] => Billy
[total_bookings] => 5
[user_id] => 4
[sales_revenue] => 1180
[net_revenue] => 1180
)
[1] => Array
(
[supplier] => XYZ1
[total_bookings] => 3
[user_id] => 2
[sales_revenue] => 642
[net_revenue] => 642
)
)
[3] => Array
(
[0] => Array
(
[supplier] => Billy
[total_bookings] => 1
[year] => 2016
[month] => 3
[user_id] => 4
[sales_revenue] => 30
[net_revenue] => 30
)
)
)
[2015] => Array(
[10] => Array
(
[supplier] => Billy
[total_bookings] => 1
[user_id] => 4
[sales_revenue] => 30
[net_revenue] => 30
)
)
)
答案 0 :(得分:0)
试试这个,让我知道:
$new_arr = array();
foreach($arr as $val){
$temp = array('supplier' => $val['supplier'], 'total_bookings' => $val['total_bookings'], 'user_id' => $val['user_id'], 'sales_revenue' => $val['sales_revenue'], 'net_revenue' => $val['net_revenue']);
array_push($new_arr[$val['year']][$val['month']], $temp);
}
print_r($new_arr);
答案 1 :(得分:0)
使用array_fill_keys
,array_column
(自PHP 5.5开始提供),array_walk
和array_diff_key
函数的解决方案:
// supposing $arr is your initial array
$years = array_fill_keys(array_column($arr, 'year'), []);
array_walk($arr, function($v) use(&$years){
if (key_exists($v['year'], $years)) {
$years[$v['year']][$v['month']][] = array_diff_key($v, ['year'=>0, 'month'=>0]);
}
});
print_r($years);
答案 2 :(得分:0)
试试这个: -
$res = [];
foreach($array as $record){
$year = $record['year'];
$month = $record['month'];
unset($record['year'],$record['month']);
$res[$year][$month][] = $record;
}
echo '<pre>'; print_r($res);