具有多维数组的多系列高图数据

时间:2013-02-18 16:17:24

标签: php arrays multidimensional-array highcharts

我试图以Highcharts使用的格式获取我的数据数组,以生成数据的多系列图表。

我的数据阵列是:

Array ( 
[answer1] => Array ( [SubQuestion 1] => 3 [SubQuestion 2] => 1 ) 
[answer2] => Array ( [SubQuestion 1] => 2 [SubQuestion 2] => 2 ) 
[answer3] => Array ( [SubQuestion 1] => 1 [SubQuestion 2] => 1 ) 
[answer4] => Array ( [SubQuestion 1] => 1 [SubQuestion 2] => 2 ) 
[answer5] => Array ( [SubQuestion 1] => 0 [SubQuestion 2] => 1 )
)

我需要将它变成Highcharts的格式:

$chartdata = array(
array("name" =>"SubQuestion 1","data"=>  array(3,2,1,1,0) ),
array("name" =>"SubQuestion 2","data"=>  array(1,2,1,2,1) )
);

任何人都可以指出我正确的方向,如何迭代我的数组创建一个HighCharts格式的新数组?

感谢所有帮助。我只想关闭循环并发布正确答案的略微修改版本:         $ chartdata = array();         foreach($ series as $ key1 => $ value1){             $ I = 0;             foreach($ value1 as $ key2 => $ value2){                 $ chartdata [$ i] ['name'] = $ key2;                 $ chartdata [$ i] ['data'] [] = $ value2;                 $ I ++;             }                 }

1 个答案:

答案 0 :(得分:1)

$myarray = Array ( 
'answer1' => Array ( 'SubQuestion 1'=> 3 , 'SubQuestion 2' => 1 ) ,
'answer2'=> Array ( 'SubQuestion 1' => 2, 'SubQuestion 2' => 2 ) ,
'answer3' => Array ( 'SubQuestion 1' => 1, 'SubQuestion 2' => 1 ) ,
'answer4' => Array ( 'SubQuestion 1' => 1, 'SubQuestion 2' => 2 ) ,
'answer5' => Array ( 'SubQuestion 1' => 0, 'SubQuestion 2' => 1 )
);


$temp = array();
$chartdata = array();
foreach($myarray as $key1 => $value1){
  foreach($value1 as $key2 => $value2){
   if(!in_array($key2, $temp)){
    $temp[] = $key2;
   }
   $chartdata[array_search($key2, $temp)]['name'] = $key2;
   $chartdata[array_search($key2, $temp)]['data'][] = $value2;
  }
}
echo '<pre>';
print_r($chartdata);