0

I am trying to get my data array in a format that is used by Highcharts to generate a multi-series chart of the data.

My data array is:

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

I need to get it into this format for 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) )
);

Can anyone please point me in the right direction as to how to iterate through my array to create a new array in the HighCharts format?

Thanks for all the help. I just wanted to close the loop and post the slightly modified version of the correct answer: $chartdata = array(); foreach($series as $key1 => $value1){ $i=0; foreach($value1 as $key2 => $value2){ $chartdata[$i]['name'] = $key2; $chartdata[$i]['data'][] = $value2; $i++; } }

2
  • why not just create it using foreach and then create your desired array? Commented Feb 18, 2013 at 16:20
  • I'd look at array_walk() to modify initial array. But transforamtion of initial array to desired output is not obvious, so maybe you'll have to use foreach and create a new transformed array. Commented Feb 18, 2013 at 16:30

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That is very close to what i need. Array ([SubQuestion 1] =>Array ( [name] => SubQuestion 1 [data] => Array ( [0] => 3 [1] => 2 [2] => 1 [3] => 1 [4] => 0 ) ) [SubQuestion 2] => Array ( [name] => SubQuestion 2 [data] => Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 ) ) ) However there is an extra 'Key'. the data should be a numerical array not an associative array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.