Could you give me some advice how to get data from this file?
I need to receive, for example, a list of stops and lines, or other data from the most nested objects, but I don't now how to do that with nested objects in JSON.
{
"stops": {
"11": "Winna-Karpacka",
"21": "Piwna",
"31": "RondoTysiąclecia",
"41": "Piątkowicka-Wiączyńska",
"51": "Taczańska",
"61": "Komarzewska",
"12": "Winna-Działki",
"22": "Piwna-Karpacka",
"32": "RondoTysiąclecia",
"42": "Piątkowicka",
"52": "Taczańska",
"62": "Komarzewska-Wiączyńska"
},
"lines": {
"1": {
"variants": {
"16": [{
"11": 0
}, {
"21": 3
}, {
"31": 5
}, {
"41": 10
}, {
"51": 12
}, {
"61": 16
}],
"61": [{
"62": 0
}, {
"52": 3
}, {
"42": 6
}, {
"32": 8
}, {
"22": 14
}, {
"12": 16
}]
},
"departures": {
"16": [
"04:00",
"04:50",
"05:40",
"06:30",
"07:20",
"08:10",
"09:00",
"10:00",
"11:00",
"12:00",
"13:00",
"14:00",
"14:50",
"15:40",
"16:30",
"17:20",
"18:10",
"19:00",
"20:00",
"21:00",
"22:00"
],
"61": [
"04:25",
"05:15",
"06:05",
"06:55",
"07:45",
"08:35",
"09:30",
"10:30",
"11:30",
"12:30",
"13:30",
"14:25",
"15:15",
"16:05",
"16:55",
"17:45",
"18:35",
"19:30",
"20:30",
"21:30"
]
}
},
"2": {
"variants": {
"25": [{
"21": 0
}, {
"31": 2
}, {
"41": 7
}, {
"51": 9
}],
"52": [{
"52": 0
}, {
"42": 3
}, {
"32": 5
}, {
"22": 11
}]
},
"departures": {
"25": [
"10:15",
"10:45",
"11:15",
"11:45",
"12:15",
"12:45",
"13:15",
"13:45",
"14:15",
"14:45",
"15:15",
"15:45",
"16:15",
"16:45",
"17:15",
"17:45"
],
"52": [
"10:30",
"11:00",
"11:30",
"12:00",
"12:30",
"13:00",
"13:30",
"14:00",
"14:30",
"15:00",
"15:30",
"16:00",
"16:30",
"17:00",
"17:30"
]
}
},
"3": {
"variants": {
"35": [{
"31": 0
}, {
"41": 12
}, {
"51": 22
}],
"53": [{
"51": 0
}, {
"41": 10
}, {
"31": 22
}]
},
"departures": {
"34": [
"01:10",
"02:10",
"03:10"
],
"43": [
"01:40",
"02:40",
"03:40"
]
}
}
}
}
I tried something like this but it doesn't work
$str = file_get_contents('dane.json');
$json = json_decode($str, true);
echo $json['stops']['11'];
json_decode, then use this function I wrote to generate the appropriate PHP code to access any specific element in your JSON.
function jsonGeneratePhp($json, $phpString = '$json') {
if (is_array($json)) {
echo "$phpString<br>";
foreach ($json as $key => $value) {
jsonGeneratePhp($value, "{$phpString}['$key']");
}
} elseif (is_object($json)) {
echo "$phpString<br>";
foreach ($json as $key => $value) {
if (is_numeric($key)) {
jsonGeneratePhp($value, "{$phpString}->{{$key}}");
} else {
jsonGeneratePhp($value, "{$phpString}->$key");
}
}
} else {
echo "$phpString = $json<br>";
}
}
$str = file_get_contents('dane.json');
$json = json_decode($str);
jsonGeneratePhp($json);
This will generate a bunch of PHP statements that correspond to each piece of your JSON data, like this:
$json
$json->stops
$json->stops->{11} = Winna-Karpacka
$json->stops->{21} = Piwna
...
Anything that ends in an = something is a value.
for example: echo $json->stops->{11}; // Winna-Karpacka
Anything that does not end in an = something is an array or an object that you can iterate with foreach.
for example: foreach ($json->stops as $stopId => $stopName) { ... }
Related
I have an object like this, and I'm working with "todos" array, only want update active status with specific indexs are given:
{
"_id": "61e7e78372d3221d2c5fb242",
"from_date": "2022/01/01 00:00:00",
"to_date": "2022/01/01 00:00:00",
"todos": [
{
"name": "sub1",
"desc": "desc1",
"active": true,
"owner": "61e6125db0f102060951aa53"
}, // index = 0
{
"name": "sub2",
"desc": "desc2",
"active": true,
"owner": "61e6125db0f102060951aa53"
}, // index = 1
...
]
}
The first I try update with: ['$set' => ['todos.0.active' => false]]
{
"0": {
"active": false
},
"name": "sub1",
"desc": "desc1",
"active": true,
"owner": "61e6125db0f102060951aa53"
},
active can be update to false, key 0 is generated. I continue try other:
array_push($pipeline, ['$set' => ['todos' => [
'$function' => [
'body' => 'function(todos) {
return todos; // or do something
}',
'args' => ['todos'],
'lang' => 'js',
]
]]]);
But todos field turn into string is "todos", not array. What wrong with $set and $function? And other operators can do the same easier like $map or $filter?
My full pipeline update:
[
{
"$set": {
"name": "First Task 1",
"desc": "This is description",
"status": "completed",
"done": 100,
"level": "medium",
"company": "BBB",
"project": "AAA",
"from_date": "2022/01/01 00:00:00",
"to_date": "2022/01/01 00:00:00",
"updated_at": "$$NOW"
}
},
{
"$set": {
"todos.1.active": false
}
},
{
"$set": {
"todos": {
"$concatArrays": [
"$todos",
[
{
"name": "sub3",
"desc": "desc3",
"active": true,
"owner": "61e6125db0f102060951aa53"
}
]
]
}
}
}
]
db.collection.updateOne(['_id' => ObjectId('')], $pipeline, ['multi' => true]})
I want to update with pipeline, not each single query.
db.collection.update({
"_id": "61e7e78372d3221d2c5fb242"
},
{
$set: {
"todos.$[elem].active": false
}
},
{
"multi": true,
"arrayFilters": [
{
"elem.name": {
$eq: "sub1"
}
}
]
})
mongoplayground
db.collection.update({
"_id": "61e7e78372d3221d2c5fb242"
},
{
$set: {
"todos.0.active": false,
"todos.2.active": false
}
},
{
"multi": true
})
mongoplayground
db.collection.update({
"_id": "61e7e78372d3221d2c5fb242"
},
[
{
$set: {
todos: {
$map: {
input: {
$range: [ 0, { $size: "$todos" } ]
},
as: "i",
in: {
$let: {
vars: {
"item": { $arrayElemAt: [ "$todos", "$$i" ] }
},
in: {
$cond: {
if: {
$in: [ "$$i", [ 0, 2 ] ]
},
then: {
"name": "$$item.name",
"desc": "$$item.desc",
"active": false,
"owner": "$$item.owner"
},
else: "$$item"
}
}
}
}
}
}
}
}
],
{
"multi": true
})
mongoplayground
helo here I have JSON data. I made it in the helper based on the day of the month and year.
here I make an attendance data report, and this is the JSON
{
"data": {
"user": {
"id_user": "13",
"name": "JHON"
},
"month": "01",
"year": "2021",
"attendace": [
{
"date": "01-01-2021",
"in": "07:24:50",
"out": "17:03:42"
},
{
"date": "03-01-2021",
"in": "07:08:50",
"out": "17:18:50"
},
{
"date": "07-01-2021",
"in": "07:03:42",
"out": "18:03:42"
}
],
"day": [
{
"day": "Friday",
"date": "01-01-2021"
},
{
"day": "Saturday",
"date": "02-01-2021"
},
{
"day": "Sunday",
"date": "03-01-2021"
},
{
"day": "Monday",
"date": "04-01-2021"
},
......
...... // to
{
"day": "Sunday",
"date": "31-01-2021"
}
]
}
}
the question is how to combine JSON absent with JSON day?
and I want to make it like this, if the absent data is blank on date 5,6,7,8 then it is automatically null
I want to like this
"day": [
{
"day": "Friday",
"date": "01-01-2021"
"data" [
{
"in": "07:03:42",
"out": "18:03:42"
}
]
},
{
"day": "Saturday",
"date": "02-01-2021"
"data" [
{
"in": null,
"out": null
}
]
},
{
"day": "Sunday",
"date": "03-01-2021"
"data" [
{
"in": "07:03:42",
"out": "18:03:42"
}
]
},
]
and this my code
pulic function get(){
$data['user'] = $this->mymodel->find($id_user);
$data['bulan'] = $bulan;
$data['tahun'] = $tahun;
$data['attendance'] = $this->mymodel->get_absen($id_user, $bulan, $tahun);
$data['day'] = hari_bulan($bulan, $tahun);
$message = array(
'status' => true,
'data' => $data
);
$this->response($message, REST_Controller::HTTP_OK);
}
$attendace = $data['attendace'];
$days = $data['day'];
$days = array_map(function($day) use ($attendace) {
$day['data'] = [];
foreach ($attendace as $visit) {
$day_date = new DateTime($day['date']);
$visit_date = new DateTime($visit['date']);
$interval = $day_date->diff($visit_date)->format('%d');
if ($interval == 0) {
$day['data'][] = [
'in' => $visit['in'],
'out'=> $visit['out']
];
}
}
if (count($day['data']) === 0)
$day['data'][] = [
'in' => null,
'out' => null
];
return $day;
}, $days);
I have following Json Data in php url
File name : house.php
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"MAIN": 225,
"PHASE": 219418523,
"G": "7TH Division",
"GI": "2031892",
"DOOR": "8907",
"Gate": {
"RG": 2,
"BNS": "4 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "81",
"AI": "8745524"
},
{
"MAIN": 300,
"PHASE": 219418523,
"G": "8TH Division",
"GI": "4526892",
"DOOR": "8877",
"GATE": {
"RG": 2,
"BNS": "5 Window",
"BS": {
"SB1": 2
},
"TQ": [
{
"Key": 1,
"Value": {
"T1": 2
}
},
{
"Key": 2,
"Value": {}
}
],
"MR": -1,
"MS": 600
},
"AA": "91",
"AI": "8758421"
}]}
I need particular data "G", "G1", "DOOR", "AA", A1" alone to display in my new php file :
completehouse.php in json format what code to give to get particular data.
<?php
$url="house.php";
$text = file_get_contents($url);
header('Content-Type: application/json');
echo $text;
?>
Currently i am using https://codebeautify.org/online-json-editor manually each time by using transform data
query : [*].{G: G, G1: G1, DOOR: DOOR, AA: AA, AI: AI} and getting output
{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"G": "7TH DIVISION",
"G1": "2031892",
"DOOR": "8907",
"AA": "81",
"AI": "8745524"
},
{
"G": "8TH DIVISION",
"G1": "4526892",
"DOOR": "8877",
"AA": "85",
"AI": "8759544"
}
]
}
Please someone help me to fix my manual work and save my time.
You can decode your json and then get the exact value of what you want.
$json = '....';
$parsed = json_decode($json,true);
$result = [];
if($parsed['Success']){ // check if your api json response is true.
foreach($parsed['Value'] as $val){
if($val['AI']> = 9000000){
$result[] = [
"G"=> $val['G'],
"GI"=> $val['GI'],
"DOOR"=> $val['DOOR'],
"AA"=> $val['AA'],
"AI"=> $val['AI']
];
}
// or what you want.
}
}
echo json_encode($result);
see demo
As you only need to manipulate the Value column so below code will keep all values same but get the specific columns from Value.
$url="house.php";
$text = file_get_contents($url);
$data = json_decode($text, true);
if ($data['Success'] === true) {
$v = [];
$columns = ["G", "GI", "DOOR", "AA", "AI"];
for ($i = 0; $i< count($data['Value']); $i++) {
foreach ($data['Value'][$i] as $key => $val) {
if (in_array($key, $columns)) {
$v[$key] = $val;
}
}
$data['Value'][$i] = $v;
}
}
$text = json_encode($data);
{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
},
This is json data fetched from live flights query. I want to be able to determine the number of stops for each flight using the [depart_at] field. So I have been struggling to get the number of occurrences of the [depart_at] field so as to derive how many stops(layovers) for each flight. I have already converted to php using the code below: But I am not getting the count.
<?php foreach ($itinerary['outbound']['flights'] as $flight ){
echo count($flight['flights']);
}?>
You can try like this:
$json = '{
"currency": "USD",
"results": [
{
"itineraries": [
{
"outbound": {
"duration": "08:35",
"flights": [
{
"departs_at": "2018-07-03T18:35",
"arrives_at": "2018-07-03T21:15",
"origin": {
"airport": "BOS",
"terminal": "A"
},
"destination": {
"airport": "YHZ"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "3713",
"aircraft": "DH4",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 5
}
},
{
"departs_at": "2018-07-03T22:20",
"arrives_at": "2018-07-04T08:10",
"origin": {
"airport": "YHZ"
},
"destination": {
"airport": "LGW",
"terminal": "N"
},
"marketing_airline": "WS",
"operating_airline": "WS",
"flight_number": "24",
"aircraft": "7M8",
"booking_info": {
"travel_class": "ECONOMY",
"booking_code": "M",
"seats_remaining": 1
}
}
]
}
}
],
"fare": {
"total_price": "653.40",
"price_per_adult": {
"total_fare": "653.40",
"tax": "178.40"
},
"restrictions": {
"refundable": true,
"change_penalties": true
}
}
}';
echo substr_count($json, 'departs_at');
You can try that way.
$countDepartsAt = 0;
foreach ($itinerary['outbound']['flights'] as $flight ){
if(array_key_exists('departs_at', $flight)) {
$countDepartsAt++;
}
}
echo $countDepartsAt;
I have this php code to return the Array from a JSON file how ever I am not able to return the objects (The Airport info structure) as well the Arrivals etc.
Apologies if this is not very clear I am fairly new to this.
Code:
$fxml_response = $client->request('GET', 'AirportBoards', ['query' => $queryParams]);
try {
$body = json_decode($fxml_response->getBody(), true);
if ($fxml_response->getStatusCode() == 200 && !array_key_exists('error', $body)) {
foreach (['arrivals', 'departures', 'enroute', 'scheduled',] as $board) {
if($body['AirportBoardsResult'][$board]) {
$boardFlights = $body['AirportBoardsResult'][$board]['flights'];
$response[$board] = $boardFlights;
}
}
} else {
$response['error'] = $body['error'];
}
} catch (Exception $e) {
echo json_encode(['error' => 'Failed to retrieve Airport Board details.']);
}
// Send back the data
header('Content-Type: application/json');
echo json_encode($response);
Json:
{
"AirportBoardsResult": {
"airport": "NZAP",
"airport_info": {
"airport_code": "NZAP",
"name": "Taupo",
"elevation": 1335.0,
"city": "Taupo",
"state": "",
"longitude": 176.084444,
"latitude": -38.739723,
"timezone": ":Pacific/Auckland",
"country_code": "NZ",
"wiki_url": "https://en.wikipedia.org/wiki/Taupo_Airport",
"alternate_ident": "TUO"
},
"arrivals": {
"num_flights": 6,
"next_offset": -1,
"flights": [{
"ident": "SDA806",
"faFlightID": "SDA806-1528092600-schedule-0000",
"airline": "SDA",
"airline_iata": "S8",
"flightnumber": "806",
"tailnumber": "ZK-PLV",
"type": "Form_Airline",
"blocked": false,
"diverted": false,
"cancelled": false,
"origin": {
"code": "NZWN",
"city": "Wellington",
"alternate_ident": "WLG",
"airport_name": "Wellington Int'l"
},
"destination": {
"code": "NZAP",
"city": "Taupo",
"alternate_ident": "TUO",
"airport_name": "Taupo"
},
"filed_ete": 3480,
"route": "KADNU1Q KAPTI WNAP2",
"filed_altitude": 210,
"display_filed_altitude": "21,000 feet",
"filed_airspeed_kts": 250,
"distance_filed": 191,
"filed_departure_time": {
"epoch": 1528265400,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:10PM",
"date": "06/06/2018",
"localtime": 1528308600
},
"estimated_departure_time": {
"epoch": 1528265889,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:18PM",
"date": "06/06/2018",
"localtime": 1528309089
},
"actual_departure_time": {
"epoch": 1528265889,
"tz": "NZST",
"dow": "Wednesday",
"time": "06:18PM",
"date": "06/06/2018",
"localtime": 1528309089
},
"departure_delay": 489,
"filed_arrival_time": {
"epoch": 1528268880,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:08PM",
"date": "06/06/2018",
"localtime": 1528312080
},
"estimated_arrival_time": {
"epoch": 1528269502,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:18PM",
"date": "06/06/2018",
"localtime": 1528312702
},
"actual_arrival_time": {
"epoch": 1528269180,
"tz": "NZST",
"dow": "Wednesday",
"time": "07:13PM",
"date": "06/06/2018",
"localtime": 1528312380
},
"arrival_delay": 300,
"status": "Arrived",
"progress_percent": 100,
"aircrafttype": "PC12",
"full_aircrafttype": "L/PC12",
"adhoc": false
}]
};
Add the airport info to the result after the loop.
if ($fxml_response->getStatusCode() == 200 && !array_key_exists('error', $body)) {
foreach (['arrivals', 'departures', 'enroute', 'scheduled',] as $board) {
if($body['AirportBoardsResult'][$board]) {
$boardFlights = $body['AirportBoardsResult'][$board]['flights'];
$response[$board] = $boardFlights;
}
}
$response['airport_info'] = $body['AirportBoardsResult']['airport_info'];
}