skip to Main Content

hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :

    ...

    }elseif ($work == "dollardate") {

    $query3 = "SELECT * FROM tabl_dollar_date";

    $result3 = $connect->prepare($query3);

    $result3->execute();

    $out3 = array();

    while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {

        $record3 = array();

        $record3["dollar"] = $row3["dollar"];

        $record3["date"] = $row3["date"];



        array_push($out3, $record3);

    }
    echo json_encode($out3);
}

?>

this code show this in json :

[  
   {  
      "dollar":"15000",
      "date":"1397-12-12"
   }
]

how can remove array from json and show the json like this :

  {  
      "dollar":"15000",
      "date":"1397-12-12"
   }

2

Answers


  1. Easiest way (according his code):

    change line

    echo json_encode($out3);
    

    to

    echo json_encode($out3[0]);
    
    Login or Signup to reply.
  2. One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record…

    $query3 = "SELECT `date`, `dollar`
        FROM `tabl_dollar_date`
        ORDER BY `date` desc
        LIMIT 1";
    $result3 = $connect->prepare($query3);
    $result3->execute();
    $row3 = $result3->fetch(PDO::FETCH_ASSOC);
    echo json_encode($row3);
    

    As you know which fields you want from the SELECT, it’s good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search