Search code examples
phpjsonmultidimensional-arrayreindexsub-array

How to re-index subarrays before json encoding?


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);
}

Solution

  • 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);
    }