Home > Software design >  Reformat json in a correct way
Reformat json in a correct way

Time:10-21

I have this php code as I am trying to execute a particular function in my php project, I code the implementation correct but I ran into a small problem.

                <?php echo '<script type="text/javascript">';

                $data = array(
                    'base' => 'USD',
                    'alter' => 'ETH',
                    'data' => array()
                );

                foreach ($cryptos as $row) {
                    $sy = $row["symbol"];
                    $data['data'][] = array(
                       "$sy"  => [
                            "rate" => 1.552000000000000,
                            "min" => 1.0077600000000000,
                            "max" => 10.077600000000000,
                            "code" => $row["symbol"],
                            "dp" => 8

                        ],

                    );
                }
                print_r("var fxCur = " . json_encode($data));

Running the code above I got this result below, That's the expected result but I want to omit [] between data

{
   "base":"USD",
   "alter":"ETH",
   "data":[
      {
         "BTC":{
            "rate": 1.552000000000000,
            "min": 1.0077600000000000,
            "max": 10.077600000000000,
            "code":"BTC",
            "dp":8
         }
      },
      {
         "ETH":{
            "rate": 1.552000000000000,
            "min": 1.0077600000000000,
            "max": 10.077600000000000,
            "code":"ETH",
            "dp":8
         }
      }
   ]
}

But actually I wanted this result

{
   "base":"USD",
   "alter":"ETH",
   "data":{
      "BTC":{
          "rate": 1.552000000000000,
          "min": 1.0077600000000000,
          "max": 10.077600000000000,
         "code":"BTC",
         "dp":8
      },
      "ETH":{
          "rate": 1.552000000000000,
          "min": 1.0077600000000000,
          "max": 10.077600000000000,
         "code":"ETH",
         "dp":8
      },
   
   }
}

CodePudding user response:

You're telling it to construct the data structure that way.

$data['data'][] = array(
  "$sy"  => [
    ...
  ]
);

That line says "append an element to $data['data'] at the next integer index and set it equal to the array e.g. [ "BTC" => [ ... ]]

I think what you want is:

$data['data'][$sy] = [
    "rate" => 1.552000000000000,
    "min" => 1.0077600000000000,
    "max" => 10.077600000000000,
    "code" => $row["symbol"],
    "dp" => 8
];
  • Related