0

Am trying to produce a json object ouput of the following

{
 name: 'creditor',
  y: 5600
}, 
{
 name: 'Supplier',
  y: 2400,
 },

In my php i have

public function getTotalInspected($ts1, $ts2){
  $inspectiondata = [];
   $truck_categories = TblTruckSubtypes::find()->all();

    foreach ($truck_categories as $truck_category) {
       $name =  $truck_category["description"];
       $trucks = TblTrucks::find()->
               where(['truck_category'=>$truck_category["id"]])->count();
       $inspectiondata[] =  ["name"=>$name,'y'=> $trucks];
     }

  return $inspectiondata;

 }

The above produces an output of the form

 {
 "name": 'creditor',
  "y": 5600
}, 
{
 "name": 'Supplier',
  "y": 2400,
 },

Note the name from the desired output and "name" in the output.

How can i get the desired output above.

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 2
    The desired output is an invalid JSON - the keys are strings, and strings must be enclosed in double quotes. – Ruslan Osmanov Aug 23 '17 at 02:39
  • am trying to produce data for https://www.highcharts.com/docs/chart-concepts/series – Geoff Aug 23 '17 at 02:40
  • You can encode the array with `json_encode`, escape JavaScript characters with `json_encode`, again, then use `JSON.parse` function on the client side, e.g. `var series = JSON.parse(= json_encode(json_encode(['name' => 'creator', 'y' => 2400])); ?>)`. – Ruslan Osmanov Aug 23 '17 at 02:56
  • Possible duplicate of [Converting PHP result array to JSON](https://stackoverflow.com/questions/2122233/converting-php-result-array-to-json) Do not try to roll your own `json_encode()`, just call the function and be done. Please research more before posting. – mickmackusa Aug 23 '17 at 03:01
  • @RuslanOsmanov after jsonParse am ending up with an array, how do i then convert the array to object – Geoff Aug 23 '17 at 03:21

1 Answers1

-1

Try with json_encode() and preg_replce()

$inspectiondata= json_encode($inspectiondata);

$inspectiondata   = preg_replace('/"([a-zA-Z]+[a-zA-Z0-
                                   9_]*)":/','$1:',$inspectiondata);
Arzoo
  • 106
  • 5