1

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?

1
  • The json array which your php is generating should work. Have a look at this link. And what's the error that you get? Commented Apr 15, 2017 at 7:59

2 Answers 2

1

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

Comments

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

Comments

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.