• 0

[PHP] Creating JSON array


Question

I'm sure this is something simple I'm missing, but I can't seem to get the right output I'm looking for.

$output['data']= array(
	"character_id" => $id,
	"name" => $name,
	"score" => $score,
	"time_played" => $time_played
	);
	
	echo json_encode($output);

Result looks like:

{
"data":{
"character_id":"5428010618035589553",
"name":"Player1",
"score":"221332661",
"time_played":"176 Days 14 Hours 31 Minutes"
}
}{"data":{"character_id":"5428019223852978081","name":"Player2","score":"216120181","time_played":"198 Days 3 Hours 15 Minutes"}}

What I want:

{
"data":[
{
"character_id":"5428010618035589553",
"name":"Player1",
"score":"221332661",
"time_played":"176 Days 14 Hours 31 Minutes"
},
{
"character_id":"5428019223852978081",
"name":"Player2",
"score":"216120181",
"time_played":"198 Days 3 Hours 15 Minutes"
}
]
}
Link to comment
https://www.neowin.net/forum/topic/1252626-php-creating-json-array/
Share on other sites

16 answers to this question

Recommended Posts

  • 0

I'll presume the character data is fetched from a database and added dynamicly.

 

You'll have to define the output['data'] as an array and keep pushing the new arrays with the character data in.

//Needs to be defined outside the loop, otherwise you'll keep resetting $output['data']
$output['data'] = array();
 
while( $something is pulled from a database )
{
    //$output['data'][] creates a new entry in the array
    $output['data'][] = array(
        "character_id" => $id,
        "name" => $name,
        "score" => $score,
        "time_played" => $time_played
    );
}
 
//Should now output the desired json
echo json_encode( $output );
  • 0

Ya data is fetched from daybreakgames api using foreach.

 

Now getting the following:

[
[
{
"character_id":"5428010618035589553",
"name":"Player1",
"score":"221332661",
"time_played":"176 Days 14 Hours 31 Minutes"
},
{
"character_id":"5428019223852978081",
"name":"Player2",
"score":"216120181",
"time_played":"198 Days 3 Hours 15 Minutes"
}
]
]

I'd like the players to be in 'data' array

 

object

->"data"

->->array

->->->"player1"

->->->"player2"

  • 0

How would I get the child objects?

{
"characters_stat_history_list":[
{
"stat_name":"deaths",
"all_time":"5091"
},
{
"stat_name":"kills",
"all_time":"15827"
},
{
"stat_name":"score",
"all_time":"25025749"
}
],
"returned":3
}

Tried this and it's not working

foreach ($json->characters_stat_history_list as $player_stats) {
		$deaths=$player_stats[0][all_time];
		$kills=$player_stats[1][all_time];
	}
  • 0
  On 06/04/2015 at 22:40, DPyro said:

How would I get the child objects?

{"characters_stat_history_list":[{"stat_name":"deaths","all_time":"5091"},{"stat_name":"kills","all_time":"15827"},{"stat_name":"score","all_time":"25025749"}],"returned":3}
If it's a json string which I assume you'll have to parse the json string into an object.

var objectWithObjects = $.parseJSON(jsonstring);

var deaths;
for(x=0;x<objectWithObjects["characters_stat_history_list"].length;x++) {
    if(objectWithObjects["characters_stat_history_list"][x]["stat_name"] == "deaths") {
        deaths = objectWithObjects["characters_stat_history_list"][x]["all_time"];
    }
}
alert("all time deaths: "+deaths);
  • 0
  On 06/04/2015 at 23:30, DPyro said:

5zaRIpp.png

If it's a json string in php you should use json_encode to change the string into an object.

And try

$json["characters_stat_history_list"]
Instead of

$json->characters_stat_history_list
  • 0

I dunno, doesn't seem to work. Only thing I've gotten to return a value is 

$deaths=$player_stats->all_time[0];
$kills=$player_stats->all_time[1];

But they're obviously not the right values.

 

According to this it should be characters_stat_history_list[0].all_time  :s

  • 0
stdClass Object
(
    [characters_stat_history_list] => Array
        (
            [0] => stdClass Object
                (
                    [stat_name] => deaths
                    [all_time] => 15716
                )

            [1] => stdClass Object
                (
                    [stat_name] => kills
                    [all_time] => 383607
                )

            [2] => stdClass Object
                (
                    [stat_name] => score
                    [all_time] => 221467298
                )

        )

    [returned] => 3
)
  • 0
$json['characters_stat_history_list'][0]['all_time']//Deaths
$json['characters_stat_history_list'][1]['all_time']//Kills
$json['characters_stat_history_list'][2]['all_time']//Score

//Edit

You should also set the second parameter of json_decode to true so you'll have json object converted to associative arrays, this will make it easier to go through it.

 

json_decode($json_string, true );

 

Otherwise the above won't work I think

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • This is the Superman film I had been waiting for. The tone was fine, yes a little more “fun” than previous outings but a lot of that came from supporting characters. Krypto was well handled, and somehow managed to not be an annoying distraction and actually a valid part of the story. Hoult was GREAT as Luthor. Genuinely so happy that this wasn’t crap. I personally enjoyed Superman Returns, despite its flaws (tried too much to hide behind the older movies, had no real fight to Superman). I enjoyed the Man Of Steel movies despite their flaws (totally that is NOT Superman). But this - this is the film I had wanted. In the UK we are far more reserved in cinemas than Americans. It’s rare that there is the whooping and hollering that we have seen from videos of US theatres, so when I say that the audience clapped at the end of this - it’s quite a big deal. As for all this “Superman has gone woke” BS - he is freaking Superman and if at any point in that movie you found yourself pooh-pooing his actions, you are just - you’re aligning your thinking with the problems and not the solutions. I adore how the movie addressed the modern world through thinly veiled allegory (Israel, online bots, perceptions of people, how they change on a dime) - that is maybe one of the greatest strengths of  comics, they rarely pull punches with that sort of thing, and look, THIS IS SUPERMAN, he’s meant to be the global boyscout and that is a strength and where he falls down sometimes, that’s just who he is and who he is meant to be. I also am glad there was no reference to the worldwide joke that is “Truth, Justice and the American way”.
    • People do it everywhere. Should be legal to be allowed to bitch slap people who put their phone on speaker in public places
    • Or Editpad 👍
    • They work like drug dealers. First we get free samples and when we like it they start charging for it. Wasn't there some uproar lately about the (possibly subbed) AI features in the new Nothing phones as well? Expect subs down the line, as AI cost a lot of money to run. And you're going to pay for it in the end 🤨
  • Recent Achievements

    • One Month Later
      Ricky Chan earned a badge
      One Month Later
    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
    • Dedicated
      MacDaddyAz earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      504
    2. 2
      ATLien_0
      207
    3. 3
      Michael Scrip
      205
    4. 4
      Xenon
      141
    5. 5
      +FloatingFatMan
      115
  • Tell a friend

    Love Neowin? Tell a friend!