Phorce
Phorce

Reputation: 4642

PHP API - Encode multiple data entries

Here is the desired output (in JSON)

{
     response: {
       code: "400",
       total_results: "100",
       listings: [
        {
           "title": "My First Application",  
           "imgage": "image1.jpg"

        },

        {
           "title": "My second Application",  
           "imgage": "image1.jpg"

        },  

       ]
     }
}

I store the response which is given to allow for status codes etc.. and the actual listings is the data. I am building a mobile application so I want to be able to put: data.title, data.image for example.

Here is what I have so far (in PHP):

 $response = array("response" =>
    array(
        "code" => "400",
        "total_results" => "100",

        "listings" => array("title" => "My first listing", "image" => "image1.jpg"),


    ),

  );

However this is wrong as it's not allowing me to have multiple listings, nor is it allowing me (inside the app) to reference title and image.

Can anyone suggest a way how I can do this so that the data is properly formatted correctly?

Upvotes: 0

Views: 90

Answers (4)

Mike Robinson
Mike Robinson

Reputation: 8965

No matter how you decide to do it (and, as you can see, "there's more than one way to do it ..."), the bottom line is that you need "an array of arrays." (Or, what might be called in some other languages, "an array of structs ...)

JSON will obligingly encode and decode any PHP data structure to-and-from a string. "Get the data-structure right," and JSON will take care of itself.

Upvotes: 0

Yassin Senhaji
Yassin Senhaji

Reputation: 77

try to make a class :

class Item{ public $title; public $image; function __construct($title, $img){ $this->title = $title; $this->image = $img; } }

So now you can do this :

$response = array("response" =>
    array(
        "code" => "400",
        "total_results" => "100",
        "listings" => array(new Item("My first listing","image1.jpg"),new Item("My second listing","image2.jpg"))
    ),
  );

Upvotes: 1

Lionnel
Lionnel

Reputation: 17

With this array did you try : $json_response = json_encode($response);

Upvotes: -2

Styphon
Styphon

Reputation: 10447

You just need to make your listings a multi-dimensional array:

$response = array("response" =>
    array(
        "code" => "400",
        "total_results" => "100",

        "listings" => array(
            (object) ["title" => "My first listing", "image" => "image1.jpg"],
            (object) ["title" => "My second listing", "image" => "image1.jpg"]
        ),


    ),

  );

I've cast the arrays in the listings as objects, as that's what your JSON structure suggested they should be.

Upvotes: 3

Related Questions