0

我有这个数组:

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'
  )

)

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

4

2 回答 2

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);

可以对其进行优化以使用更少的内存。但是,如果您没有太多数据(不是每秒数百万条横幅和数百个请求),则不需要它。

于 2013-09-23T14:19:15.353 回答
0

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

arrayName.join(delimiter);

或者简单地循环数组:

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

str.slice(-1);
于 2013-09-23T14:06:59.623 回答