0

This is my current JSON output:

{
   0: {
      label: 1509521006,
      value: 12.324711
   },
   1: {
      label: 1509531448,
      value: 12.700929
   }
}

What should I do to make my JSON output like this:

[
 [
   1509521006,
   12.324711
 ],
 [
   1509531448,
   12.700929
 ]
]

This is my PHP code for convert my array to JSON

if ($count > 0) {
    $categoryArray = array();
    foreach ($sensObj as $dataset) {
        array_push($categoryArray, array(
            "label" => $dataset["time"],
            "value" => $dataset["value"]
        ));
    }
    print json_encode($categoryArray);
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
noovin
  • 27
  • 4

3 Answers3

0

You're building the output JSON, so just do it in the different way you need:

<?php
if ($count > 0) {
    $categoryArray = array();
    foreach ($sensObj as $dataset) {
        array_push($categoryArray, array(
            $dataset["time"],
            $dataset["value"]
        ));
    }
    print json_encode($categoryArray);
}

Or, as an alternative syntax:

if ($count > 0) {
    $categoryArray = [];
    foreach ($sensObj as $dataset) {
        $categoryArray[] = [
            $dataset['time'],
            $dataset['value'],
        ];
    }
    print json_encode($categoryArray);
}
Jordi Nebot
  • 3,355
  • 3
  • 27
  • 56
0

what you trying to print object or array because your result in object and you want in them in array .

[ [ 1509521006, 12.324711 ], [ 1509531448, 12.700929 ] ]

you can create this json by using this code

<?php
if ($count > 0){ 
   $categoryArray = array();
 foreach ($sensObj as $dataset) { 
     array_push($categoryArray,array( $dataset["time"],  $dataset["value"])); 
}
 print json_encode($categoryArray); } 

Try This.

Sanjeev Kumar
  • 85
  • 1
  • 9
0

You only need to re-index the subarrays. Just decode the json, reindex the subarrays, then re-encode it.

Here is a one-liner for you:

Code: (Demo)

echo json_encode(array_map('array_values',json_decode($your_json,true)));

Output:

[["1509521006","12.324711"],["1509531448","12.700929"]]

I believe to implement with your code, you would write:

echo json_encode(array_map('array_values',$sensObj));
// this assumes $sensObj is an array and not an object array
mickmackusa
  • 43,625
  • 12
  • 83
  • 136