I am using randonuser API to generate dummy images. The API returns JSON that I have used json_decode to decode and using print_r, I got the array below:
Array
(
[results] => Array
(
[0] => Array
(
[user] => Array
(
[gender] => male
[name] => Array
(
[title] => mr
[first] => dwight
[last] => evans
)
[location] => Array
(
[street] => 6822 hunters creek dr
[city] => fresno
[state] => vermont
[zip] => 63409
)
[email] => dwight.evans44#example.com
[username] => ticklishostrich542
[password] => ebony
[salt] => 4xuAIjmh
[md5] => 648f472ff152a194c410d774ff9a4b9d
[sha1] => f23cc7ffd2b8980d10de86bccc85068ecf9b7b45
[sha256] => fec06f7df352a06aab9c30af9d7ab9b5b81dc0bd6b7567b59fba1a731dea6bba
[registered] => 1129218274
[dob] => 409533355
[phone] => (797)-563-6160
[cell] => (200)-718-4014
[SSN] => 213-46-5200
[picture] => Array
(
[large] => http://api.randomuser.me/portraits/men/98.jpg
[medium] => http://api.randomuser.me/portraits/med/men/98.jpg
[thumbnail] => http://api.randomuser.me/portraits/thumb/men/98.jpg
)
[version] => 0.4.1
)
[seed] => cf744a697a08f256
)
. .. .....
and so on.
I just need the large key value under parent picture. How do I loop through it using a foreach statement?
Just access it as you normally would:
$data = json_decode('that json string', true);
foreach($data['results'] as $value) {
echo $value['user']['picture']['large'];
}
Use json_decode($var, true), then you'll have an array, and looping will be easier.
Related
I have been trying to extract the following data for each student from a large multidimensional array (Shown further down)
Data -> gender,
Data -> grade,
Data -> name -> first,
Data -> name -> last,
Data -> name -> middle,
Data -> student_number,
Data -> ID
I have tried various options through searching including Slice, Splice, and a for loop.
Every attempt has been met with failure on all or some of the data. I have never been able to get to the 3rd nested data of First, Middle, and Last name.
How can I take a large multidem array like this, and extract the data listed above in a foreach loop so I can import it into a database? I feel like it is alot simpler than I am making it. I have not included any code as I have yet to have anything that seems remotely useful.
Here is a sample array below. Thanks!
Array
(
[data] => Array
(
[0] => Array
(
[data] => Array
(
[gender] => M
[dob] => 7/17/2008
[email] =>
[grade] => 2
[schools] => Array
(
[0] =>12345
)
[school] => 12345
[created] => 2018-04-16T14:01:00.437Z
[name] => Array
(
[first] => Jacob
[last] => Smith
[middle] => Rabbitboom
)
[location] => Array
(
[zip] =>
[address] =>
[city] =>
[lat] =>
[lon] =>
[state] =>
)
[district] => 123456
[last_modified] => 2018-04-16T14:01:00.437Z
[race] =>
[hispanic_ethnicity] =>
[graduation_year] =>
[student_number] => 1234567
[credentials] => Array
(
[district_username] =>
)
[id] => 123456
)
[uri] =>
)
[1] => Array
(
[data] => Array
(
[gender] => F
[dob] => 7/17/2008
[email] =>
[grade] => 2
[schools] => Array
(
[0] =>12346
)
[school] => 12345
[created] => 2018-04-16T14:01:00.437Z
[name] => Array
(
[first] => Jason
[last] => Smith
[middle] => RobesPerrie
)
[location] => Array
(
[zip] =>
[address] =>
[city] =>
[lat] =>
[lon] =>
[state] =>
)
[district] => 123456
[last_modified] => 2018-04-16T14:01:00.437Z
[race] =>
[hispanic_ethnicity] =>
[graduation_year] =>
[student_number] => 1234568
[credentials] => Array
(
[district_username] =>
)
[id] => 123459
)
[uri] =>
)
The easiest approach might be to extract the nested data arrays and loop that:
foreach(array_column($array['data'], 'data') as $data) {
echo $data['gender'];
echo $data['name']['first'];
}
If schools is variable length then you'll need to loop that or implode(', ', $data['schools']).
I've an associative array. I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
[id] => 184
[firstName] => skg
[lastName] => s
[address] => Array
(
[address1] => sakthi
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
)
[jobOrder] => Array
(
[id] => 88
[title] => Tech Analyst
)
)
[1] => Array
(
[candidate] => Array
(
[id] => 852
[firstName] => mso cool
[lastName] =>
[address] => Array
(
[address1] =>
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
)
[jobOrder] => Array
(
[id] => 57
[title] => Tester
)
)
And Another Array like this :
[rating] => Array
(
[0] => 7
[1] => 5
[2] =>
)
How to get merge this array value into previous array values like
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
[id] => 184
[firstName] => skg
[lastName] => s
[address] => Array
(
[address1] => sakthi
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
[rating] => 7
)
[jobOrder] => Array
(
[id] => 88
[title] => Tech Analyst
)
)
[1] => Array
(
[candidate] => Array
(
[id] => 852
[firstName] => mso cool
[lastName] =>
[address] => Array
(
[address1] =>
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
[rating] => 5
)
[jobOrder] => Array
(
[id] => 57
[title] => Tester
)
)
I tried lot of tricks but couldn't get the desired array format. Can any one help me in this to get the desired array? Thanks in advance.
$arr = array(); //filled with data
$rating = array(); //filled with rates
foreach ( $rating as $key =>$rate ) {
$arr['data'][ $key ]['rating'] = $rate;
}
<?php
$arr=Array(
'data'=>Array(
0=>Array('candidate'=>Array()),
1=>Array('candidate'=>Array())
)
);
$rating=Array(7,5);
foreach($rating as $key=>$val){
$arr['data'][$key]['rating']=$val;
}
print_r($arr);
Returns:
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
)
[rating] => 7
)
[1] => Array
(
[candidate] => Array
(
)
[rating] => 5
)
)
)
i am working on a UPS tracking API, i have called the API to track the package, i am getting the right response, but in array format, i am new to json decoding, please tell me how to parse this in PHP, do i have to create multiple objects in PHP? i am attaching the output as well as the PHP code.
PHP Code
if (isset($_POST['af0'])) {
if (preg_match('/^[a-z\d_]{4,80}$/i', $_POST['trackingNumber'])) {
$cleanTrackingNumber = $_POST['trackingNumber'];
$someArray = upsTrack("$cleanTrackingNumber");
echo '<pre>'; print_r($someArray); echo '</pre>';
} else {
echo 'Invalid tracking number... sigh...';
}
}
Output
Array
(
[TRACKRESPONSE] => Array
(
[RESPONSE] => Array
(
[TRANSACTIONREFERENCE] => Array
(
[XPCIVERSION] => 1.0
)
[RESPONSESTATUSCODE] => 1
[RESPONSESTATUSDESCRIPTION] => Success
)
[SHIPMENT] => Array
(
[SHIPPER] => Array
(
[SHIPPERNUMBER] => A6161A
[ADDRESS] => Array
(
[ADDRESSLINE1] => 132 E 43RD ST
[CITY] => NEW YORK
[STATEPROVINCECODE] => NY
[POSTALCODE] => 10017 4019
[COUNTRYCODE] => US
)
)
[SHIPTO] => Array
(
[ADDRESS] => Array
(
[CITY] => TORONTO
[STATEPROVINCECODE] => ON
[POSTALCODE] => M5V3X1
[COUNTRYCODE] => CA
)
)
[SHIPMENTWEIGHT] => Array
(
[UNITOFMEASUREMENT] => Array
(
[CODE] => LBS
)
[WEIGHT] => 3.20
)
[SERVICE] => Array
(
[CODE] => 011
[DESCRIPTION] => STANDARD
)
[REFERENCENUMBER] => Array
(
[CODE] => 13
[VALUE] => A6161AD9HPK
)
[SHIPMENTIDENTIFICATIONNUMBER] => 1ZA6161A6832763249
[PICKUPDATE] => 20140519
[SCHEDULEDDELIVERYDATE] => 20140521
[PACKAGE] => Array
(
[TRACKINGNUMBER] => 1ZA6161A6832763249
[ACTIVITY] => Array
(
[ACTIVITYLOCATION] => Array
(
[ADDRESS] => Array
(
[CITY] => SECAUCUS
[STATEPROVINCECODE] => NJ
[COUNTRYCODE] => US
)
)
[STATUS] => Array
(
[STATUSTYPE] => Array
(
[CODE] => I
[DESCRIPTION] => DEPARTURE SCAN
)
[STATUSCODE] => Array
(
[CODE] => DP
)
)
[DATE] => 20140520
[TIME] => 053000
)
[MESSAGE] => Array
(
[CODE] => 01
[DESCRIPTION] => On Time
)
[PACKAGEWEIGHT] => Array
(
[UNITOFMEASUREMENT] => Array
(
[CODE] => LBS
)
[WEIGHT] => 3.20
)
[REFERENCENUMBER] => Array
(
[CODE] => 19
[VALUE] => MMTD71EUY061A
)
)
)
)
)
If you already have the output in Array format then you don't have anything more to do with json decoding.
You can use $someArray to get any data from the array.
It's up to you if you want to just display it or save it, for example in a database.
What is it you trying to accomplish?
This question is a follow up from this Now for my follow up question I also have this object on page:
Array
(
[registrants] => Array
(
[0] => Registrant Object
(
[title] => D C
[link] => **********
[id] => ***************
[updated] => 2013-03-06T12:11:49-05:00
[lastName] => C
[firstName] => D
[email] => *********
[personalInformation] => PersonalInformation Object
(
[cellPhone] =>
[label] =>
[addr1] =>
[addr2] =>
[addr3] =>
[city] =>
[state] =>
[postalCode] =>
[province] =>
[country] =>
[phone] =>
)
[businessInformation] => BusinessInformation Object
(
[fax] =>
[website] =>
[blog] =>
[company] =>
[jobTitle] =>
[department] =>
[label] =>
[addr1] =>
[addr2] =>
[addr3] =>
[city] =>
[state] =>
[postalCode] =>
[province] =>
[country] =>
[phone] =>
)
[customInformation1] => Array
(
)
[customInformation2] => Array
(
)
[registrationStatus] => REGISTERED
[registrationDate] => 2013-03-06T12:11:49-05:00
[guestCount] => 0
[paymentStatus] => NA
[orderAmount] =>
[currencyType] =>
[paymentType] =>
[costs] => Array
(
)
)
[1] => Registrant Object
(
[title] => Test Test
[link] => ****
[id] => *************
[updated] => 2013-03-06T12:47:47-05:00
[lastName] => Test
[firstName] => Test
[email] => ***************
[personalInformation] => PersonalInformation Object
(
[cellPhone] =>
[label] =>
[addr1] =>
[addr2] =>
[addr3] =>
[city] =>
[state] =>
[postalCode] =>
[province] =>
[country] =>
[phone] =>
)
[businessInformation] => BusinessInformation Object
(
[fax] =>
[website] =>
[blog] =>
[company] =>
[jobTitle] =>
[department] =>
[label] =>
[addr1] =>
[addr2] =>
[addr3] =>
[city] =>
[state] =>
[postalCode] =>
[province] =>
[country] =>
[phone] =>
)
[customInformation1] => Array
(
)
[customInformation2] => Array
(
)
[registrationStatus] => REGISTERED
[registrationDate] => 2013-03-06T12:47:47-05:00
[guestCount] => 0
[paymentStatus] => NA
[orderAmount] =>
[currencyType] =>
[paymentType] =>
[costs] => Array
(
)
)
)
[nextLink] =>
)
So following the same theory I am retriving the values like this:
<?php echo $Registrant->lastName; echo $Registrant->firstName; echo $Registrant->email; ?>
but this only retrieves the first lastname and firstname from [0] => Registrant Object not from 1 => Registrant Object how to i get all of the first names and last names?
Thank everyone for there interest and there time.
Kind regards
Chris
To explain your scenario a bit further than other answers.
You have an array of (Registrant) objects here. This is actually an associative array (as all PHP arrays) with indices from 0 - 1.
$registrantObjects[0] // would give first Registrant object
$registrantObjects[1] // would give second Registrant object
You can access them both. But if you want to iterate the array (i.e. going over all elements and do the same for each one), you should use a loop.
PHP has a nice foreach loop for this use case:
foreach ($registrantObjects as $registrant) {
// $registrant is a Registrant object here
echo $registrant->lastName;
}
You could also try this:
foreach ($registrantObjects as $index => $registrant) {
// $registrant is a also Registrant object here
// But we have a variable $index, too. It represents the current 'key'
// We have a normal (numbered) array thus the keys are [0..1]
echo $registrant->lastName;
}
And both loops are equal to this for loop:
for ($i = 0, $len = count($registrantObjects); $i < $len; $i++) {
// $registrantObjects[$i] gives a Registrant object
}
Lets say the object you printed is "$RegistrantObjects"
You can do the following thing :
foreach ($RegistrantObjects as $registrant)
{
echo $registrant->lastName;
}
Within the foreach, the $registrant object will be accessible the same way that you code accesses it.
Try the below code;
<?php
foreach($Registrant as $reg) {
echo $reg->firstname;
echo $reg->lastname;
}
?>
I have created an application that sends out a SOAP request and gets a response back. This is working fine but I am having trouble looping through all the individual results in order to organize them into an array. Here is the response:
stdClass Object
(
[FITgymlistResult] => stdClass Object
(
[FITgym] => Array
(
[0] => stdClass Object
(
[GYMGUID] => 45124542-bca5-e211-8f4a-00155d007722
[GYMNAME] => Belfast
[Postcode] =>
[Phone] =>
[Email] => belfast#fitspace.co.uk
)
[1] => stdClass Object
(
[GYMGUID] => aece7776-bca5-e211-8f4a-00155d007722
[GYMNAME] => Bournemouth
[Addressline1] => St Paul's Road
[Postcode] =>
[Phone] =>
[Email] => Bournemouth#fitspace.co.uk
)
[2] => stdClass Object
(
[GYMGUID] => 8eaa258e-bca5-e211-8f4a-00155d007722
[GYMNAME] => Bradford
[Postcode] =>
[Phone] =>
[Email] => Bradford#fitspace.co.uk
)
[3] => stdClass Object
(
[GYMGUID] => 935bfdca-bca5-e211-8f4a-00155d007722
[GYMNAME] => Islington
[Postcode] =>
[Phone] =>
[Email] => holloway#fitspace.co.uk
)
[4] => stdClass Object
(
[GYMGUID] => fe104008-bda5-e211-8f4a-00155d007722
[GYMNAME] => Lincoln
[Postcode] =>
[Phone] =>
[Email] => lincoln#fitspace.co.uk
)
[5] => stdClass Object
(
[GYMGUID] => ff3cd339-bda5-e211-8f4a-00155d007722
[GYMNAME] => Mitcham
[Postcode] =>
[Phone] =>
[Email] => Mitcham#fitspace.co.uk
)
[6] => stdClass Object
(
[GYMGUID] => 496e8149-bda5-e211-8f4a-00155d007722
[GYMNAME] => Nottingham
[Postcode] =>
[Phone] =>
[Email] => Nottingham#fitspace.co.uk
)
[7] => stdClass Object
(
[GYMGUID] => 48f26656-bda5-e211-8f4a-00155d007722
[GYMNAME] => Sheffield
[Postcode] =>
[Phone] =>
[Email] => Sheffield#fitspace.co.uk
)
[8] => stdClass Object
(
[GYMGUID] => 1c136968-bda5-e211-8f4a-00155d007722
[GYMNAME] => Woolwich
[Postcode] =>
[Phone] =>
[Email] => Woolwich#fitspace.co.uk
)
)
)
)
What would be the best and quickest way to loop through each individual item in this response?
Thanks
Let say that this object is stored in $ret variable and you want to store individual results in array $data.
$data = array();
foreach($ret->FITgymlistResult->FITgym as $item)
{
$data[] = get_object_vars($item);
}
get_object_vars dumps as array all variables from the object and theirs values
also
in foreach loop you can access, print or store item data like this:
echo $item->email;
$test = $item->GYMNAME;
$data[] = array($item->email, $item->GYMNAME);
Use a foreach loop on the array:
foreach( $response->FITgymlistResult->FITgym as $row )
{
var_dump( $row->GYMGUID, $row->GYMNAME );
}
See also: stdClass object and foreach loops