0

I am trying to produce the following JSON from MySQL database using PHP. How do I go about doing it in PHP lets say using the explode function for getting the array into the JSON object. I don't know about getting the JSON object inside an object. I just need to separate PHP files to achieve the following.

<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM users';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
 while ($row = $q->fetch(PDO::FETCH_ASSOC)){
     array_push($array, $row);
 }
$json = json_encode($array);
echo $json;
Database::disconnect();?>

Array inside a JSON object:

[
{
  "firstName":"John", 
  "lastName":"Doe",
  "images": ['image1','image2','image3']
}, 
{
  "firstName":"Anna",   
  "lastName":"Smith",
  "images": ['image1','image2','image3']
},
{
 "firstName":"Peter", 
 "lastName":"Jones",
 "images": ['image1','image2','image3']
 }
]

JSON object inside an object:

[
{
  "firstName":"John", 
  "lastName":"Doe",
  "cover": {
            "cover_id": "0858699703",
            "source": "www.myimages.co.zw/images/photo",
            "offset_y": "0"
          }
}, 
{
  "firstName":"Anna",   
  "lastName":"Smith"
  "cover": {
            "cover_id": "0858699703",
            "source": "www.myimages.co.zw/images/photo",
            "offset_y": "0"
          }
},
{
 "firstName":"Peter", 
 "lastName":"Jones"
 "cover": {
            "cover_id": "0858699703",
            "source": "www.myimages.co.zw/images/photo",
            "offset_y": "0"
          }
 }
]
4
  • 1
    Just use json_encode() on your actual result set Commented Dec 6, 2014 at 19:42
  • Show the PHP code that is querying your database Commented Dec 6, 2014 at 19:51
  • <?php include 'database.php'; $pdo = Database::connect(); $sql = 'SELECT * FROM user'; $q = $pdo->prepare($sql); $q->execute(array($sql)); $array = array(); while ($row = $q->fetch(PDO::FETCH_ASSOC)){ array_push($array, $row); } $json = json_encode($array); echo $json; Database::disconnect(); ?> Commented Dec 6, 2014 at 19:57
  • Check the update i have added the php Commented Dec 6, 2014 at 20:03

1 Answer 1

1
 <?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM test';
$q = $pdo->prepare($sql);
$q->execute(array($sql));
$array = array();
 while ($row = $q->fetch(PDO::FETCH_ASSOC)){

     $row_array['name'] = $row['name'];
     $row_array['surname'] = $row['surname'];
     $row_array['images'] =  explode(" ", $row['images']);

     array_push($array, $row_array);
 }
$json = json_encode($array);
echo $json;
Database::disconnect();
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.