I'm a beginner in PHP and my PHPreturns json array but returns this:
[{"ContentID":"1","con_Model":"CAR_NAME","Picture_path":"localhost\/1.jpg"},{"ContentID":"2","con_Model":"CAR_NAME1","Picture_path":"localhost\/1.jpg"}]
And I want this:
["content": {"ContentID":"1","con_Model":"CAR_NAME","Picture_path":"localhost\/1.jpg"},{"ContentID":"2","con_Model":"CAR_NAME1","Picture_path":"localhost\/1.jpg"}]
My PHP code :
<?php
$array = array();
require("config.inc.php");
$query="SELECT Content.ContentID,Content.con_Model,Picture.Picture_path from Content INNER JOIN Picture ON Content.ContentID = Picture.ContentID LIMIT 25;";
try {
$stmt = $db->prepare($query);
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
json_encode($array);
print(json_encode($array));
?>
Try this
$json_result = array("content" => $array); // puts content in string before your json
print(json_encode($json_result)); // print encoded json
The problem with your desired format is, it is not a valid JSON. A valid one has to look like this:
{<key>:<value>, …}
You could place your key in front of the array. It would be a valid JSON.