我应该怎么做才能在php中获得这样的数组



我有一个数组,如下所示:

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框架。但我不知道我应该用什么方法来得到这样的数组?

有人能给我指路吗?

-

提前谢谢。

第三次幸运!我最初遗漏了这个问题中的一些微妙之处。试试下面的代码——它有点古怪,但它应该适合你。

我假设您的原始数组名为$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)

希望这有帮助:)

编辑

中eval.in的实时示例

假设您的数组存储在$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. 

相关内容

  • 没有找到相关文章