1
1
123 1232014-11-16 07:29:34
PHP
123 123, 2014-11-16 07:29:34

How to convert json from PHP?

I have 2 tables. The first one is meteo_temp0{id,temp,hum,date}. The second one is meteo_temp1{id,temp,hum,date}.
I need to return the following json:

{
  "temp0":[
    {"temp":25,"hum":50,"date":"2014-11-16 10:22:34"}
  ],
  "temp1":[
    {"temp":28,"hum":53,"date":"2014-11-16 10:25:30"}
  ]
}

Now it returns as you already understood this json:
{"temp0":8,"temp1":4,"hum0":72,"hum1":92,"date0":"2014-11-16 10:07:17","date1":"2014-11-16 10:07:20"}

Right now I have the following PHP:
/* Query Temp0 */
      $query_temp0 = $connection->prepare("SELECT temp, hum, date FROM meteo_temp0 ORDER BY id DESC LIMIT 1");
      $query_temp0->execute();
      
      $result_temp0 = $query_temp0->fetchAll();
    /* /Query Temp0 */
    /* Query Temp1 */
      $query_temp1 = $connection->prepare("SELECT temp, hum, date FROM meteo_temp1 ORDER BY id DESC LIMIT 1");
      $query_temp1->execute();
      
      $result_temp1 = $query_temp1->fetchAll();
    /* /Query Temp1 */
    
    echo json_encode(array(
      "temp0" => $result_temp0[0]["temp"],
      "temp1" => $result_temp1[0]["temp"],
      "hum0" => $result_temp0[0]["hum"],
      "hum1" => $result_temp1[0]["hum"],
      "date0" => $result_temp0[0]["date"],
      "date1" => $result_temp1[0]["date"]
    ), JSON_NUMERIC_CHECK);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2014-11-16
@mistergalynsky

$result = new stdClass;
$result->temp0 = array( 'temp'=> $result_temp0[0]["temp"], 'hum'=> $result_temp0[0]["hum"], ... );
$result->temp1 = ...;

Obviously

F
FanatPHP, 2014-11-16
@FanatPHP

This is one of those questions that a person must decide for himself, just a little thought.
You have all the data: the original data, the desired output format, the ability to add data to the array.
It's embarrassing to ask strangers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question