为高级图重组数组

时间:2013-09-23 13:59:39

标签: php arrays

我有这个数组:

array (
  0 => 
  array (
    'banner' => 'banner1',
    'dayofweek' => '1',
    'count' => '3',
  ),
  1 => 
  array (
    'banner' => 'banner1',
    'dayofweek' => '2',
    'count' => '1',
  ),
  2 => 
  array (
    'banner' => 'banner2',
    'dayofweek' => '2',
    'count' => '3',
  )
)

我需要在highcharts中使用它来获得两个不同的向量,其中dayofweek为day,count为value。这应该是highcharts数组:

series:[
    {
        name:'banner1',
        data:[3,1,0,0,0,0,0,]
    },
    {
        name:'banner2',
        data:[0,3,0,0,0,0,0,]
    }
]

我想以这种方式获得数组:

array (
  0 => 
  array (
    'banner' => 'banner1',
    'counts' => '3,1,0,0,0,0,0'
  ),
  1 => 
  array (
    'banner' => 'banner2',
    'counts' => '0,3,0,0,0,0,0'
  )

)

如何解析数组以获得我需要的格式?

2 个答案:

答案 0 :(得分:1)

实际上你需要的是这样的东西:

$initialArray = ...;
$temp = array();
foreach ($initialArray AS $a) {
    if (!isset($temp[ $a['banner'] ])) {
        $temp[ $a['banner'] ] = array_fill(0, 7, 0);
    }
    $temp[ $a['banner'] ][ $a['dayofweek'] - 1 ] = intval($a['count']);
}

$series = array();
foreach ($temp AS $banner => $counts) {
    $obj = new stdClass();
    $obj->banner = $banner;
    $obj->counts = $counts;
    $series[] = $obj;
}

echo json_encode($series);

可以优化使用更少的内存。但是如果你没有太多的数据(不是数百万的横幅和每秒数百个请求),那就不需要了。

答案 1 :(得分:0)

如果您的意思是像php implode(),那么请尝试:

arrayName.join(delimiter);

或者只是循环数组:

var str = '';
$.each(arrayName, function(i, num){
    str += num + ',';
})

str.slice(-1);