• 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

    • And this is why I wait at least a week after a Patch Tuesday to update the servers...
    • Windows is a scam for many decades, it's good if some people are realizing it now
    • Latest Patch Tuesday has broken DHCP Server in all Windows Server editions by Usama Jawad Microsoft released Patch Tuesday updates for Windows and Windows Server releases roughly a week ago, on June 10. In the latter, the release contained new functions for Narrator scan mode, along with tons of fixes for File Explorer, GDI+, Hyper-V, and more. At that time, Microsoft noted a known issue for Noto fonts, where Chinese, Japanese, and Korean text appears blurry or unclear under certain conditions. Now, it has highlighted another known issue following user reports. For the past couple of days, users on Reddit have been reporting issues with the DHCP service after applying the latest Patch Tuesday update. Apparently, rebooting the system fixes the issue, which can be understandably annoying. Now, Microsoft has updated the documentation for the June 10 release notes across Windows Server 2016, 2019, 2022, and 2025, to mention that the DHCP Server service may "intermittently" stop working after installing Patch Tuesday's update, which will impact IP renewal processes on client machines. Redmond has assured customers that it is working on a fix, which will likely be rolled out within the next few days. Of course, this problem is rather frustrating for IT admins, and that annoyance is reflected in the Reddit thread where customers are blaming Microsoft's software quality assurance practices. The fact that it's currently unclear when a fix will be rolled out may further add to customer grievances. For those unaware, the DHCP Server service in Windows is responsible for network management such as allocation and configuration of IP addresses in a centralized environment with robust logging and monitoring mechanisms. And for those keeping track, this is not the only Windows Server issue that has cropped up in recent memory. Last month, Microsoft pushed an out-of-band (OOB) hotfix to patch a Hyper-V bug that was plaguing the platform. Of course, one can argue that problems like these are happening because of incomplete testing, but it is also important to remember that Windows is running on hundreds of millions of devices all over the globe, so comprehensive test case coverage is very difficult, if not impossible.
    • And still, no Windows Hello support for protected "tabs" in the "old"/Win32 OneNote app, a feature that was available for a long time in the UWP version. Please, Microsoft, get back to feature parity...
    • Like jupe, for me, the most exciting news from Windows for a few weeks ( / months ?) now is the return of the clock in the taskbar calendar. I filed a feedback hub post so long ago about this. Finally!
  • Recent Achievements

    • Week One Done
      patrickft456 earned a badge
      Week One Done
    • One Month Later
      patrickft456 earned a badge
      One Month Later
    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      617
    2. 2
      ATLien_0
      281
    3. 3
      +FloatingFatMan
      174
    4. 4
      Michael Scrip
      153
    5. 5
      Steven P.
      124
  • Tell a friend

    Love Neowin? Tell a friend!