I am making calls to an API
I have the response as an associative array so that I can use:
$field = $response['nameOfKey'];
However, some of the values for keys are themselves arrays like the following:
{
"Title": "Mr",
"Forenames": "Steve",
"Surname": "Williams",
"CountryOfBirth": 1,
"EmailAddress": "john.doe#email.com",
"EmailType": "Personal",
"BirthDate": "\/Date(632880000000)\/",
"Suffix": null,
"NationalInsuranceNumber": null,
"PrimaryAddress": {
"Address1": "Flat 1",
"Address2": "Oxford Street",
"City": "London",
"County": "London",
"Postcode": "L12456",
"Country": 1
},
"AdditionalAddresses": [
{
"Address1": null,
"Address2": null,
"City": null,
"County": null,
"Postcode": null,
"Country": 0,
"AddressType": 0
}
],
"PrimaryTelephone": {
"Number": "123456789",
"DialingCode": 1,
"TelephoneType": 1
},
"AdditionalTelephone": [
{
"Number": "223456789",
"DialingCode": 2,
"TelephoneType": 2
}
],
"BankAccount": {
"AccountName": "John Doe Account",
"AccountNumber": "123456789",
"SortCode": "123456"
},
"PrimaryCitizenship": {
"CountryOfResidency": 1,
"TaxIdentificationNumber": "AB12CD34EF56"
},
"AdditionalCitizenship": [
{
"CountryOfResidency": 0,
"TaxIdentificationNumber": null
}
],
"ExternalCustomerId": "91",
"ExternalPlanId": "91",
"PlanType": 10
}
So at the moment to get Forename I can just do $forename = $decodedResponse["Forenames"]; but I'm quite baffled at trying to get values from the inner arrays.
I thought I could do something like this:
foreach($decodedResponse as $data)
{
foreach($data['TelephoneNumbers'] as $tel)
{
echo $tel['Number']; die();
}
}
Essentially loop through the original Associative array and then loop through a specific key to get its values.
Your should use foreach for following array items: AdditionalAddresses, AdditionalTelephone and AdditionalCitizenship. Otherwise just chain array keys. See examples:
$forename = $decodedResponse['Forenames'];
$address2 = $decodedResponse['PrimaryAddress']['Address2'];
foreach ($decodedResponse['AdditionalTelephone'] as $tel) {
echo $tel['Number'];
}
Related
I have question, is it possible not to duplicate the array object by looping on it? Right now I used laravel as my backend
I have here my response which is the exchange object duplicate itself.
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
]
Now my goal is to push the exchange without duplication:
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
}
]
Here is what my foreach loop like and how i push the array object.
$myArray = [];
foreach($exchange_check as $primary_array) {
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
array_push($myArray, (object)[
'exchange' => $primary_array,
'exchange_list' => $second_array,
]);
}
}
}
Thanks
You should add exchange data to array only once in first loop:
$myArray = [];
foreach($exchange_check as $primary_array) {
$idx = array_push($myArray, ['exchange' => $primary_array]);
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
//array_push() returns the new number of elements in the array,
//to get currently added array element we should subtract 1 from this number
$myArray[$idx-1]['exchange_list'][] = $second_array;
}
}
}
And in second loop add only exchange_list data to array.
Im posting a multipart with text and files and trying to pass data to form, but these data are separated, so I want to combine them.
$request->request->all()
$request->files->all()
$form = $this->createForm(ParkingType::class, new Parking());
$form->submit($INeedToPassTheCombinedArray);
if ($form->isValid()) {
return $form->getData();
}
Both arrays have the same structure.
For example:
$request->request->all()
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"places": [{
"total": 123,
"name": "test",
"address": "test"
},
{
"total": 123,
"name": "test",
"address": "test"
}
]
}]
}
$request->files->all()
{
"parkings": [{
"generalInfo": "File.pdf",
"places": [{
"logo": "File1.png"
},
{
"logo": "File2.png"
}
]
}]
}
I want to combine then in one single array, getting this:
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"generalInfo": "File.pdf",
"places": [{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
]
}]
}
I tried using array_merge, but the result is a single array which contain 2 arrays. It is not adding the data of one array in the respective position of the other array.
I want to know if there is some method for do this automatically and elegant.
Hope this will solve your problem
$data1 = json_decode($data,true);// first post array
$data2 = json_decode($file,true);//second file array
foreach($data1['parkings'] as $key=>&$val){ // Loop though one array
$val2 = $data2['parkings'][$key]; // Get the values from the other array
$val += $val2; // combine 'em
foreach($val['places'] as $k=>&$v){
$val3 = $val2['places'][$k]; // Get the values from the other array
$v += $val3; // combine 'em
}
}
echo json_encode($data1);
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [
{
"total": 4,
"capacity": 928,
"places": [
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
],
"generalInfo": "File.pdf"
}
]
}
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
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
I have done a query for getting all data's under same id from other table.There are more than 2 data's under same id.
I need to display all data 's under same id like an array.
Here is my sql query:
"SELECT incident.*,entry.*,fighter.*
FROM register_incident AS incident JOIN
register_entry_points AS entry
ON entry.incident_id = incident.incident_id
JOIN add_fire_fighters AS fighter
ON entry.entrypoint_id = fighter.entry_point_id
WHERE incident.incident_id=:incident_id"
I get a response like,
"data":[
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"incident_id": "5",
"user_id": "16",
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": "300",
"time_in": "10:30:00",
"time_out": "11:45:00",
"duration": "01:15",
"notes": "Test"
},
But i need to display it like,
"data": [
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter":{
{
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
}
}
}]
How it is possible?
If I get a ResultSet out of a Query with one or more 1:n relationships, I take the result like this sample.
$Result = array();
foreach($Records as $Record) {
// key 1
$key1 = $Record['incident_id'];
if(isset($Result[$key1])) {
$cuIncident=$Result[$key1];
}
else {
$cuIncident=array(
'incident_id' => $key1,
'user_id' => $Record['user_id'],
//......
'fighter' => array()
);
$Result[$key1] = $cuIncident;
}
// key 2
$key2 = $Record['fighter_id'];
if(isset($cuIncident['fighter'][$key2])) {
$cuFighter = $cuIncident['fighter'][$key2];
}
else {
$cuFighter = array(
'fighter_id' => $key2,
'entry_point_id' => $Record['entry_point_id'],
//......
'key3array' => array()
);
$cuIncident['fighter'][$key2] = $cuFighter;
}
// key 3
// ....
If a key is a multi value key, you have to combine these keys like:
$key3 = $Record['key3prop1']."/".$Record['key3prop2'];
if(isset($key3Array[$key3])) ......