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);
Related
$json_string = '{
"response_code": 200,
"info": {
"days": [
{
"code": "A",
"runs": "111"
},
{
"code": "B",
"runs": "222"
},
{
"code": "C",
"runs": "333"
}
],
"name": "SUPER MARIO",
"number": "010203",
"classes": [
{
"points": "6523",
"name": "ABC",
"available": "N"
},
{
"points": "4253",
"name": "XYZ",
"available": "N"
},
{
"points": "2323",
"name": "JOHN",
"available": "N"
},
{
"points": "5236",
"name": "TAMIL",
"available": "N"
}
]
}
}';
$jsondata = $json_string;
$arr = json_decode($jsondata, true);
foreach($arr as $k=>$v)
{
echo $k."<br>";
}
it prints
response_code
info
But, I need the results like this
6523 ABC
4253 XYZ
2323 JOHN
5326 TAMIL
I have tried and achieved this above results using this below code. But, I want to do it using foreach loop. How do list out all information using foreach?
echo "".$arr['info']['classes'][0]['points']." ".$arr['info']['classes'][0]['name']."<br/>";
echo "".$arr['info']['classes'][1]['points']." ".$arr['info']['classes'][1]['name']."<br/>";
echo "".$arr['info']['classes'][2]['points']." ".$arr['info']['classes'][2]['name']."<br/>";
echo "".$arr['info']['classes'][3]['points']." ".$arr['info']['classes'][3]['name']."<br/>";
You should foreach your array key
foreach($arr['info']['classes'] as $k=>$v)
{
echo $v['points']." " . $v['name']."<br>";
}
I have a json reply from an api and i want some data.
the response looks like this:
{
"user_id": null,
"flight_info": {
"YU24268": {
"seat": {
"width": 45.72,
"pitch": 73.66
},
"delay": {
"ontime_percent": 0.66666669,
"max": 53,
"mean": 37,
"min": 28
}
},
"delay": {
"ontime_percent": 0.67741936,
"max": 305,
"mean": 33,
"min": 0
}
}
},
"travelpayouts_api_request": true,
"clean_marker": "75089",
"currency": "usd",
"internal": false,
"airports": {
"ORY": {
"rates": "12",
"city_code": "PAR",
"country_code": "FR",
"country": "France",
"time_zone": "Europe/Paris",
"name": "Paris Orly Airport",
"city": "Paris"
},
"SXF": {
"rates": "27",
"city_code": "BER",
"country_code": "DE",
"country": "Germany",
"time_zone": "Europe/Berlin",
"name": "Schonefeld Airport",
"city": "Berlin"
}
}
I use this code to find the airport i need (from the IATA code), but i can not get the city.
function find_city_from_IATA($my_value, $key1)
{
foreach ($key1->airports as $key=>$value) {
echo $key;
echo $my_value;
if ($key==$my_value) {
$city = json_decode($key1->airports,true);
// echo $key1->airlines['U2']->city;
$city = $city->city;
echo $city;
return $city;
}
}
}
How can i get the city name based on the airport IATA? (iata is the three letter code key that airports objects have).
Something like this:
$airport_code = 'ORY';
// $my_irpost_string is your json string
$data = json_decode($my_json_string, true);
$city = $data['airports'][$airport_code]['city'];
print($city);
You don't need foreach, as you already know the code. This means that your foreach + comparison is just array value # code.
This is a well known antipattern: https://softwareengineering.stackexchange.com/questions/348682/what-is-the-for-case-antipattern
Good morning guys!
I'm having a hard time trying to figure out how to arrange the following JSON:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
Into this:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology", "Bachelor in Sociology",
"Number": "53","109",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}]
}
Basically, put the same degrees in one place and have all the names of said degree separated by a comma
I already have this JSON decoded into a variable:
$data = json_decode($topDegrees[1]["diplomas"],true);
Thanks in advance for your help!
I came up with this
$json = <<<JSON
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
JSON;
$data = json_decode( $json, true );
$degrees = $data['degrees'];
$names = array_column($degrees, 'degree');
$count = array_count_values($names);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
foreach ( array_flip($duplicates) as $degree ) {
$filter = array_filter($degrees, function($var) use ($degree) {
return ( $var['degree'] === $degree );
});
$names = [];
$numers = [];
foreach ( $filter as $item ) {
$names[] = $item['Name'];
$numbers[] = $item['Number'];
}
$indices = array_keys($filter);
$index = array_shift($indices);
$degrees[$index]['Name'] = $names; // = join(', ', $names);
$degrees[$index]['Number'] = $numbers; // = join(', ', $numbers);
while ( count($indices) ) {
unset($degrees[array_shift($indices)]);
}
}
$data['degrees'] = $degrees;
print_r(json_encode($data));
// {"showElement":"1","degrees":[{"Name":["Bachelor in Psychology","Bachelor in Sociology"],"Number":["53","109"],"degree":"Bachelor's Degree"},{"Name":"Certificate","Number":"56","degree":"Certificate"},{"Name":"High School Diploma","Number":"28","degree":"High School"}]}
Your wanted json output is not valid, i have made an array structure in its place. If you want comma separated text, just use the join statements I've commented out.
$str = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor\'s Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor\'s Degree"
}]
}';
$str_arr = json_decode($str);
foreach($str_arr->degrees as $k=>$val){
if($val->degree == 'Bachelor\'s Degree'){
$new['Bachelor'][] = $val;
}else{
$new[] = $val;
}
}
foreach($new['Bachelor'] as $aa){
$nameStr[]= $aa->Name;
$numStr[] = $aa->Number;
}
$nameStr = implode(', ', $nameStr);
$numStr = implode(', ', $numStr);
$degree = 'Bachelor\'s Degree';
$new[] = (object) array($nameStr, $numStr, $degree);
unset($new['Bachelor']);
echo $json = json_encode($new);
echo "<pre>"; print_r(json_decode($json));
Hope this helps.
Demo here
This should do it:
<?php
$json = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelors Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelors Degree"
}]
}';
$items = json_decode($json, true);
$orderedItems = [];
$final = ['showElement' => 1];
foreach ($items['degrees'] as $item) {
$orderedItems[$item['degree']]['Name'][] = $item['Name'];
$orderedItems[$item['degree']]['Number'][] = $item['Number'];
$orderedItems[$item['degree']]['degree'] = $item['degree'];
}
foreach ($orderedItems as $order) {
$order['Name'] = (count($order['Name']) > 1) ? $order['Name'] : $order['Name'][0];
$order['Number'] = (count($order['Number']) > 1) ? $order['Number'] : $order['Number'][0];
$final['degrees'][] = [
'Name' => $order['Name'],
'Number' => $order['Number'],
'degree' => $order['degree']
];
}
echo json_encode($final);
I've looked a little and found an answer that partially does what I am interested in doing, see: Sorting a JSON array in PHP
I have some decoded JSON that looks like this, just a sample.
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
What I would like to do is sort everything alphabetically so that it is easier to read and uniform. So that what I would see is:
{
"accounts": [
{
"css": null,
"connected": 0,
"must_approve_upload": 0,
"password_expire": 90,
"settings": {
"link_external_whitelist": "",
"link_first_study_only": "0",
"other_ingress_tags": "",
"update_study_source_on_notify": "1"
},
"share_via_gateway": 0,
"vanity": "medpics"
}
],
"page": {
"more": 0,
"number": 1,
"rows": 5000,
}
"status": "OK"
}
Every element is sorted alphabetically. Is that possible ?
Pretty straightforward
$json = <<<JSON
{
"status": "OK",
"page": {
"rows": 5000,
"more": 0,
"number": 1
},
"accounts": [
{
"connected": 0,
"settings": {
"link_first_study_only": "0",
"update_study_source_on_notify": "1",
"link_external_whitelist": "",
"other_ingress_tags": ""
},
"must_approve_upload": 0,
"css": null,
"share_via_gateway": 0,
"password_expire": 90,
"vanity": "medpics"
}
]
}
JSON;
$json = json_decode($json, true);
function ksort_recursive(&$array) {
ksort($array);
foreach ($array as &$value) {
if (is_array($value)) {
ksort_recursive($value);
}
}
}
ksort_recursive($json);
print_r($json);
Proof of solution here
https://3v4l.org/qUAA0
For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things
Here is my json
{
"profile": [
{
"id": "123456",
"hostId": null,
"description": [
{
"id": "name",
"value": "foo"
},
{
"id": "name2",
"value": "foo2"
},
{
"id": "bio",
"value": "heyyyy"
},
{
"id": "location",
"value": "somewhere"
}
],
"ishere": true
}
]
}
I want to manipulate it to have this
{
"id": "123456",
"host": null,
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere",
"ishere": true
}
with this (after a json_decode)
foreach ($array->profileUsers[0]->settings as $item) {
$out2[$item->id] = $item->value;
}
I only have
{
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere"
}
Thank you
This should do the trick:
$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
$obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
if(is_array($item)) {
$new_array[$item['id']] = $item['value'];
}
else {
$new_array[$key] = $item;
}
}
Hardcoded this, hope it will help.