Reputation: 1970
Firstly what I am trying is creating a pie chart using google chart api. There I have to feed an javascript array of array. Now what I have in server side is an php array of following structure:
[
{
"name": "a",
"price": 25200
},
{
"name": "b",
"price": 13500
}
]
What I need is:
[
[
"a": 25200
],
[
"b": 13500
]
]
What I have so far - used the following php function to convert.
public function convert($packages){
$packageShare = array(array());
$count = count($packages);
for($i = 0; $i < $count; $i++){
$pack = array();
$pack[$packages[$i]['name']] = $packages[$i]['price'];
$packageShare[$i] = $pack;
}
return $packageShare;
}
But the output was not what I want. Here is what the above function returns:
[
{
"a": 25200
},
{
"b": 13500
}
]
N.B. I need to feed this array in google chart api
which takes something like this in javascript.
[ [0, 0], [1, 10], [2, 12] ]
What can be the standard way to feed?
Upvotes: 1
Views: 41
Reputation: 28529
for [ [0, 0], [1, 10], [2, 12] ] format, it's an array of array. You can get this with
$output = array_map(function($v){return [$v['name'], $v['price']];}, $array);
print_r(json_encode($output));
output:
[["a",25200],["b",13500]]
Here is also other format,
<?php
//Enter your code here, enjoy!
$array = array(array('name'=>'a', 'price'=>25200),array('name'=>'b', 'price'=>13500));
print_r(json_encode($array));
echo "\n";
$output = array_map(function($v){return [$v['name'], $v['price']];}, $array);
print_r(json_encode($output));
echo "\n";
$output1 = array_map(function($v){return array($v['name'] => $v['price']);}, $array);
print_r(json_encode($output1));
echo "\n";
output:
[{"name":"a","price":25200},{"name":"b","price":13500}]
[["a",25200],["b",13500]]
[{"a":25200},{"b":13500}]
Upvotes: 1
Reputation: 362
public function convert($packages){
$a = json_decode($packages,true);
$count = sizeof($a);
for($i = 0; $i < $count; $i++){
$b[][$a[$i]['name']]=$a[$i]['price'];
}
return $b;
}
Output of print_r($b)
will be
Array ( [0] => Array ( [a] => 25200 ) [1] => Array ( [b] => 13500 ) )
Upvotes: 0