Some Java Guy
Some Java Guy

Reputation: 5118

DB Array to expected javascript format

I am implementing Highcharts in my application. It needs data in specific format.

The data in my table is as follows

enter image description here

The javascript needs data in below format

enter image description here

When I var_dump my x_axis array and y_axis array, I get below result

enter image description here

Which php functions should I use to format my array elements and pass to that JavaScript in that format?

data:[
     [<? echo PHP_some_function(" ' ", x_axis) ?>, <? echo (y_axis) ?>]   //quotes for x, no quotes for y value
]  //Moreover it should run for all the values in x_axis and y_axis

I need some logic here..

My final graph would look like

enter image description here

Upvotes: 7

Views: 238

Answers (4)

dmi3y
dmi3y

Reputation: 3522

probably array combine and than json encode and replace? just in case for diversity;)

<?php 

$x_axis = array(
'Safari', 'Opera', 'fireFox'
);

$y_axis = array(
10, 30.4, 50
);

$keyFilled = array_combine($x_axis, $y_axis);

arsort($keyFilled);

$jsonData = json_encode($keyFilled);

$jsonDataReplaced = str_replace(array(',', '{', '}', ':'), array('],[', '[', ']', ','), $jsonData);
echo '<pre>';
var_dump('['.$jsonDataReplaced.']');

?>

output is:

string(45) "[["fireFox",50],["Opera",30.4],["Safari",10]]"

http://phpfiddle.org/main/code/jq4-cgb

Upvotes: 0

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

The problem is your query.

It should be like the following.

SELECT x_axis, y_axis FROM yourTableName;

This way you'll get exactly the format that Highcharts needs. You just have to insert it inside an array.

Upvotes: 2

Naftali
Naftali

Reputation: 146302

[<? echo "'". json_encode($x_axis). "', " . json_encode($y_axis) ?>]

Demo: http://codepad.org/G5JAtXWu

Nix that I was confused.

What you want to do is this:

foreach($x_axis as $key=>$x) {
    echo "['" . $x . "', " . $y_axis[$key] . "]";
}

Demo: http://codepad.org/SKNk1VaX

To wrap it all up:

$d = array();
foreach($x_axis as $key=>$x) {
    $d[] = "['" . $x . "', " . $y_axis[$key] . "]";
}
echo json_encode($d);

Demo: http://codepad.org/KhofwXCi

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72837

Assuming:

$x_axis = array('Safari', 'Opera', 'Firefox', 'IE', 'Chrome', 'Others');
$y_axis = array(10, 6, 40.5, 20, 10.6, 0.5);

This should work:

$data = array();
$length = count($x_axis);
for ($i = 0; $i < $length; $i++) {
    $data[] = array($x_axis[i], $y_axis[i]);
}

Upvotes: 1

Related Questions