JSON sort by key which is in second level - php

Hi is there any way to sort JSON before parsing? i want to sort by OutcomeDateTime. This is my JSON
{
"State of Origin 2014":{
"1471137":{
"EventID":1471137,
"ParentEventID":1471074,
"MainEvent":"State Of Origin Series 2014",
"OutcomeDateTime":"2014-06-18 20:10:00.0000000",
"Competition":"State of Origin 2014",
"Competitors":{
"ActiveCompetitors":3,
"Competitors":[
{
"Team":"New South Wales (2 - 1)",
"Win":"2.15"
},
{
"Team":"New South Wales (3 - 0)",
"Win":"3.05"
},
{
"Team":"Queensland (2 - 1)",
"Win":"3.30"
}
],
"TotalCompetitors":3,
"HasWinOdds":true
},
"EventStatus":"Open",
"IsSuspended":false,
"AllowBets":true
},
"1471074":{
"EventID":1471074,
"ParentEventID":0,
"MainEvent":"State Of Origin Series 2014",
"OutcomeDateTime":"2014-07-09 20:10:00.0000000",
"Competition":"State of Origin 2014",
"Competitors":{
"ActiveCompetitors":2,
"Competitors":[
{
"Team":"New South Wales",
"Win":"1.33"
},
{
"Team":"Queensland",
"Win":"3.30"
}
],
"TotalCompetitors":2,
"HasWinOdds":true
},
"EventStatus":"Open",
"IsSuspended":false,
"AllowBets":true
}
},
"State of Origin 2014 Game 2":{
"3608662":{
"EventID":3608662,
"ParentEventID":3269132,
"MainEvent":"New South Wales v Queensland",
"Competitors":{
"ActiveCompetitors":39,
"Competitors":[
{
"TeamName":"New South Wales 6-10",
"Win":"4.70"
},
{
"TeamName":"Queensland 91+",
"Win":"201.00"
}
],
"TotalCompetitors":39,
"HasWinOdds":true
},
"EventStatus":"Open",
"IsSuspended":false,
"AllowBets":true
}
}
}
This is my code
foreach ($json_a as $root_element => $childnode) {
echo("{<br />");
foreach( $childnode as $cKey => $subChild) {
if($subChild['ParentEventID']=='0')
{
echo("Australian Rules : [");
echo("<br />");
echo("{<br />");
echo "MainEvent: ".$subChild['MainEvent'];
echo "<br />OutcomeDateTime: ".$subChild['OutcomeDateTime'];
echo "<br />Competitors:[ <br />{";
if (is_array($subChild['Competitors']['Competitors']) and count ($subChild['Competitors']['Competitors']) == 2 ) {
foreach($subChild['Competitors']['Competitors'] as $compKey => $compVal) {
// Since your array contains Team and TeamName , I use array_key_exists to check whick key to use
$teamName = array_key_exists('Team',$compVal) ? $compVal['Team'] : $compVal['Name'];
$win = $compVal['Win'];
echo "<br />Team: ".$teamName;
echo "<br />Win: ".$win;
echo "<br /> } , {";
}
}
}
}
I want to sort my data by OutcomeDateTime but latest data should be Time.Now+10minutes . My sorting element is inside second level. Is there any way to sort by OutcomeDateTime and get top 3 results?

Related

How do I get a list of players with foreach from my json file?

I want a list of every player and the time.
I tried
<?php foreach ($status->players as $player) { echo $player.'<br />'; } ?>
But that didn't work for me. Does anybody know how I can get a list of the players and the time?
"name":"Xanth Cluster-Genesis Pt 2 1.5xXP 4xT 3xG - (v342.2)",
"map":"Gen2",
"password":false,
"maxplayers":50,
"players":[
{
"name":"Cody",
"raw":{
"score":0,
"time":5477.548828125
}
},
{
"name":"antoniogelardi9",
"raw":{
"score":0,
"time":4328.5205078125
}
},
{
"name":"yrittz",
"raw":{
"score":0,
"time":671.528564453125
}
}
],
"bots":[
],
"connect":"0000",
"ping":145
}
This way:
<?php
$inputJson =
<<<JSON
{
"name":"Xanth Cluster-Genesis Pt 2 1.5xXP 4xT 3xG - (v342.2)",
"map":"Gen2",
"password":false,
"maxplayers":50,
"players": [
{
"name":"Cody",
"raw":{
"score":0,
"time":5477.548828125
}
},
{
"name":"antoniogelardi9",
"raw":{
"score":0,
"time":4328.5205078125
}
},
{
"name":"yrittz",
"raw":{
"score":0,
"time":671.528564453125
}
}
],
"bots":[
],
"connect":"0000",
"ping":145
}
JSON;
$arr = json_decode($inputJson);
foreach ($arr->players as $player) {
echo $player->name . ": " . $player->raw->time . "\n";
}

php read of a json file - i can not read the multi tier elements

I am trying to read a json file in php, i can retrieve the root parts of the file, however whatever i try, i can not read the innner parts(child) of the json file, any help would be great
here is the json file
{
"orderId":"112-1567223-2156269x",
"legacyOrderItemId":"0218943273x4778",
"orderItemId":"2068965x7409001",
"asin":"B01K9RxxB0GQ",
"title":"xippro decs",
"merchantId":"A3H7UYG3T9xx6JDM",
"quantity":1,
"version3.0":{
"customizationInfo":{
"surfaces":[
{
"name":"Surface 1",
"areas":[
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":13,
"y":218
},
"name":"Line 1",
"Dimensions":{
"width":382,
"height":53
},
"label":"Your Text Here",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"Ruth's"
},
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":144,
"y":258
},
"name":"Customization 2",
"Dimensions":{
"width":119,
"height":17
},
"label":"Date (EST)",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"1969"
}
]
}
]
}
},
"customizationInfo":{
"aspects":[
{
"title":"Your Text Here",
"text":{
"value":"Ruth's"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
},
{
"title":"Date (EST)",
"text":{
"value":"1969"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
}
]
},
"version":"2.0"
}
and my php code is below
<?php
$file = file_get_contents('16532135318050.json', true);
$character = json_decode($file,false,400);
//print_r ($character);
echo $character->orderId . "<Br>";
echo $character->legacyOrderItemId . "<Br>";
echo $character->orderItemId . "<Br>";
echo $character->asin . "<Br>";
echo $character->merchantId . "<Br>";
echo $character->quantity . "<Br>";
echo $character->version3.0->customizationInfo->surfaces->areas[0]->colorName; // does not work
echo $character->version3.0->customizationInfo->surfaces->areas->colorName; // does not work
?>
Two issues:
version3.0 isn't a valid identifier - you should use {"version3.0"} instead.
surfaces is an array, so you should use surfaces[0]
this might work
$character->{"version3.0"}->customizationInfo->surfaces[0]->areas[0]->colorName
The reason it doesn't work is because $character->version3.0->customizationInfo->surfaces is an array and needs to be dereferenced accordingly:
$character->{'version3.0'}->customizationInfo->surfaces[0]->areas[0]->colorName

array com problema json multidimensional

I am trying to get a data that is in an array inside another array, I did a search by the forum and google and I made several attempts without success.
It seems like an easy catch but I'm breaking my head all day and I can not.
I'm leaving below my JSON code and my last attempt to pass to PHP.
Thankful.
CODE JSON:
{
"ordens_de_servico": [
{
"oser_numero_os": 23932944,
"oser_nome_solicitante": "ED PI - CAMPO MAIOR",
"oser_dt_abertura": "27/03/2018",
"oser_pontos_refer_endereco": null,
"oser_observ_reclamacao": null,
"oser_prioridade": null,
"servico": {
"serv_cod_servico": 60,
"serv_descr_servico": "CORTE POR DEBITO"
},
"cliente": {
"nome": "ANTONIO WELTON DA SILVA OLIVEIRA",
"telefone": " "
},
"unidade_consumidora": {
"unid_ident_uc": 10945024,
"logr_nome_logr_expandido": null,
"medidor": "A2006171",
"latitude": " -4.711808",
"longitude": "-41.793455"
},
"faturas": [
{
"total_fatura": "23.01"
},
{
"total_fatura": "17.88"
},
{
"total_fatura": "23.01"
},
{
"total_fatura": "21.9"
},
{
"total_fatura": "22.92"
}
]
}
]
}
CODE PHP
<?php
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
$os = $json_data['ordens_de_servico'][0]['oser_numero_os']. PHP_EOL;
$data = $json_data['ordens_de_servico'][0]['oser_dt_abertura']. PHP_EOL;
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
echo $os."<p>";
echo $data."<p>";
echo $cod_serv."<p>";
echo $total_fatura."<p>";
?>
I tried looping unsuccessfully on the fatura
$json_data = json_decode($json,false);
foreach ( $json_data->ordens_de_servico as $valor){
echo 'FATURA:'.$valor->faturas->total_fatura."<p>".PHP_EOL;
echo PHP_EOL;
}
At a minimum, you are missing the [0] on these two lines:
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
They need to be:
$cod_serv = $json_data['ordens_de_servico'][0]['servico']['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico'][0]['faturas'][0]['total_fatura']. PHP_EOL;
Example of looping through elements in arrays:
foreach($json_data['ordens_de_servico'] as $key => $value){
echo $value["oser_numero_os"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
}
}

Illegal String offset with multi-level json decode

I am having some issues trying to pull some data from a multi-level json url. I can get everything else except for a certain nested section.
{
"name": "NewNationsPnW",
"count": 10,
"frequency": "Every 15 mins",
"version": 31,
"newdata": false,
"lastrunstatus": "success",
"thisversionstatus": "success",
"nextrun": "Wed Jan 13 2016 22:57:30 GMT+0000 (UTC)",
"thisversionrun": "Wed Jan 13 2016 22:42:30 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"Nation": {
"href": "https:\/\/politicsandwar.com\/nation\/id=30953",
"text": "Renegade States"
},
"Founded": "01\/13\/2016",
"Alliance": "None",
"Continent": "North America",
"property7": "",
"index": 1,
"url": "https:\/\/politicsandwar.com\/nations\/"
}
]
}
}
The following code works to display that nested area but I would like to get it to individual outputs.
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$json = json_decode($response, true);
//echo '<pre>'; print_r($results);
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1;
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
I have tried the following
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1['text'];
echo $stat1['href'];
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
but I get
Illegal string offset 'text' in parse.php on line 10
Illegal string offset 'href' in parse.php on line 11
As well as it only displays
hhRR01/13/2016 - None - North America
hhFFhhDD01/13/2016 - None - Asia
I am sure I am doing something that is simple to fix but being a rookie, I am messing it all up.
Your nested loop is unnecessary, and the cause of your errors:
foreach($json['results']['collection1'] as $stat) {
echo $stat['nation']['text'];
echo $stat['nation']['href'];
}
There is no need to convert a perfectly good JSON object data structure to an array.
<?php
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$j = json_decode($response );
foreach ($j->results->collection1 as $collection1 ) {
echo $collection1->Nation->href;
echo $collection1->Nation->text;
if($collection1->Alliance == 'None') {
echo sprintf("%s - %s - %s<br />",
$collection1->Founded,
$collection1->Alliance,
$collection1->Continent
);
}
}

returning json from the lastfm api

So I am trying to create a jquery/ajax autocomplete form that uses the last.fm api to autocomplete the title of a song to whatever the user is typing, the problem im having is that I can not seem to get the last fm data to return in the proper json format. this is the format that my jquery plugin (link to autocomplete) would like returned:
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
and here is essentially what im doing in my php script the returns the json to the autocomplete plugin:
$titleName = "what's my age";
$limit = 1;
$results = Track::search($titleName, $limit);
print_array($results);
echo "<ul>";
while ($title = $results->current()) {
echo $limit;
echo "<li><div>";
echo "Artist: " . $title->getArtist() . "<br>";
echo "Album: " . $title->getAlbum() . "<br>";
echo "Duration: " . $title->getDuration() . "<br>";
echo "getWiki: " . $title->getWiki() . "<br>";
echo "name: " . $title->getName() . "<br>";
echo "</div></li>";
$jsonArray['suggestions'] = array('Name'.$limit => $title->getName(), 'Artist'.$limit => $title->getArtist());
$limit++;
$title = $results->next();
}
echo "</ul>";
print_array($jsonArray);
echo json_encode($jsonArray);
the echo and print statments are just for testing, but this is what the json_encode is returning:
{"suggestions":{"Name2":"Blink vs. Jay-Z - what's my age again","Artist2":"Dj Tech1"}}
and this is what is being returned (via the echo testing):
1
Artist: Blink 1-82
Album:
Duration: 0
getWiki:
name: What's My Age Again?
2
Artist: Dj Tech1
Album:
Duration: 0
getWiki:
name: Blink vs. Jay-Z - what's my age again
so i know the code is working properly so is the sdk autocomplete etc. i also understand that am deleting the array in the while loop each time it loops through and i have not worked a fix out for that yet, but that issue aside, the json is not returning in the requested format and i can not seem to find the proper way to construct the array in order to get it in the proper format, any ideas?
$suggestionsArr['suggestions'] = [];
foreach (range(1,3) as $key => $value) {
array_push($suggestionsArr['suggestions'], ['name' => 'Song1', 'artist' => 'Artist1']);
}
echo json_encode($suggestionsArr);

Categories