我有一个数组如下:
Array
(
[Sep] => Array
(
[Support Help Desk] => 24.67
[Development] => 7.74
[Consulting Services] => 4.04
)
[Oct] => Array
(
[Support Help Desk] => 14.38
[Business Activity] => 1.92
[Maintenance Tasks] => 1.00
[Development] => 2.11
)
)
我想要这样的数组:
Array
(
[Support Help Desk] => 24.67,14.38
[Development] => 7.74,2.11
[Consulting Services] => 4.04,0
[Business Activity] => 0,1.92
[Maintenance Tasks] => 0,1.00
)
我正在使用php和zend框架。 但我不知道应该用什么方法来获得这样的数组?
有人可以指导我吗?
-
提前致谢。
答案 0 :(得分:0)
我假设您的原始数组名为$data
。
// first we need to 'normalise' or fill in the blanks in the contents of the sub array
// get a unique list of all the keys shared - doing it manually here
$keys = ['Support Help Desk', 'Business Activity', 'Maintenance Tasks', 'Development', 'Consulting Services'];
// create a default array with $keys, assigning 0 as the value of each
$default = array_fill_keys($keys, 0);
// next fill in the blanks...
// get the diff (missing keys) between the current element and the default array
// merge the missing key/value pairs
array_walk($data, function(&$month, $key, $default) {
$diff = array_diff_key($default, $month);
$month = array_merge($diff, $month);
}, $default);
// now the array is normalised
// flatten the array... where there are duplicate values for a key, and
// there will be in all cases now including default values
// a sub array is created
$merged = call_user_func_array('array_merge_recursive', $data);
// finally loop over the merged array
// and implode each array of values into a comma separated list
foreach ($merged as &$element) {
if (is_array($element)) {
$element = implode(', ', $element);
}
}
// done :)
var_dump($merged);
收率:
array (size=5)
'Business Activity' => string '0, 1.92' (length=7)
'Maintenance Tasks' => string '0, 1' (length=4)
'Support Help Desk' => string '24.67, 14.38' (length=12)
'Development' => string '7.74, 2.11' (length=10)
'Consulting Services' => &string '4.04, 0' (length=7)
希望这会有所帮助:)
修改强>
答案 1 :(得分:0)
如果每个月您可能有不同的密钥并且您事先并不知道它们,则可以使用下面的代码($ month_array是您的预处理阵列)。
$new_array = array();
foreach($month_array as $month => $month_data) {
foreach($month_data as $data => $data_value) {
$new_array[$data] = array();
}
}
foreach($month_array as $month => $month_data) {
foreach($new_array as $data => $data_value) {
if(isset($month_data[$data])) {
$new_array[$data][] = $month_data[$data];
} else {
$new_array[$data][] = 0;
}
}
}
foreach ($new_array as &$key) {
$key = implode(", ", $key);
}
答案 2 :(得分:0)
假设您的数组存储在$main_arr
中,结果数组为$result_arr
。
$result_arr = array();
foreach ($main_arr as $month) {
foreach ($month as $key => $val) {
if (!isset($result_arr[$key])) {
$result_arr[$key] = array($val);
} else {
array_push($result_arr[$key], $val);
}
}
}
foreach ($result_arr as $key => $val) {
$result_arr[$key] = implode(', ', $val);
}
print_r($result_arr); //Final output.