0

I want a json output to look like this;

[{ title:"Dynamic Title 1", content:"Dynamic content 1" },
{ title:"Dynamic Title 2", content:"Dynamic content 2" }]

I have decided to use php's json_encode() to produce this json output. But I am puzzled how should the input array to json_encode look like to produce this json output?

Thank you.

2
  • The json output isn't valid. When you do a decode you will only get the information in the first object. All the answers are correct if you had [] brackets around this. Commented Mar 19, 2014 at 3:21
  • Thanks. I made the correction. Commented Mar 19, 2014 at 3:23

3 Answers 3

3
$input = array(
   array('title'=>"Dynamic Title 1", 'content'=>"Dynamic content 1"),
   array('title'=>"Dynamic Title 2", 'content'=>"Dynamic content 2")
);

json_encode($input);

Codepad

Sign up to request clarification or add additional context in comments.

4 Comments

@TunZarniKyaw That is exactly the reason you're able to edit other's answers.
@Marty ... yes, but, it is just a very small typo
@TunZarniKyaw What I mean is that for small typos in an otherwise correct answer, the edit feature should be used :-)
Not exactly sure how I put a 0 in json heh, maybe I got abducted by 4l13ns. Edit: Oh, somebody edited my post with it I see :)
1

You can make the items like this:

$arrayItem = array( "title" => "Dynamic Title1", "content" => "Dynamic content1" )

If you want an array that have the items, you can add them to the array like this:

$array = array(); $array[] = $arrayItem;

And then encode the entire array or the $arrayItem separately if it's your purpose.

Comments

1

You can use json_encode method of PHP, it returns the JSON representation of a value

$phparray = array(
        array("title"=>"Dynamic Title 1", "content"=>"Dynamic content 1"),
        array("title"=>"Dynamic Title 2", "content"=>"Dynamic content 2")
    );    
// You can simply get the JSON string like this
$json = json_encode($phparray);

// OR if your php version is >= 5.4.0
$json = json_encode($phparray, JSON_PRETTY_PRINT);

Ref: json_encode

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.