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']).
Related
I am Working with MWS for the first time and hoping to create a program that uses the ListMatchingProducts request to average out the prices of every product that matches a query.
It should be a very simple program, but I am having trouble retrieving data.
First I make the call and get amazon's xml sheet, Then I convert the xml to an array.
Print_R shows that the array looks something like this:
Array ( [ListMatchingProductsResult] => Array ( [Products] => Array ( [Product] => Array ( [0] => Array ( [Identifiers] => Array ( [MarketplaceASIN] => Array ( [MarketplaceId] => ATVPDKIKX0DER [ASIN] => 0786866020 ) ) [AttributeSets] => Array ( [ItemAttributes] => Array ( [Author] => Array ( [0] => Stephen C. Lundin [1] => Harry Paul [2] => John Christensen ) [Binding] => Hardcover [Brand] => Hyperion [Color] => White [Creator] => Ken Blanchard [Edition] => 1 [Feature] => Great product! [ItemDimensions] => Array ( [Height] => 8.25 [Length] => 5.50 [Width] => 0.00 [Weight] => 0.54 ) [IsAdultProduct] => false [Label] => Hyperion [Languages] => Array ( [Language] => Array ( [0] => Array ( [Name] => english [Type] => Published ) [1] => Array ( [Name] => english [Type] => Original Language ) [2] => Array ( [Name] => english [Type] => Unknown ) ) ) [ListPrice] => Array ( **[Amount] => 21.00** [CurrencyCode] => USD ) [Manufacturer] => Hyperion [ManufacturerMaximumAge] => 1188.0 [ManufacturerMinimumAge] => 156.0 [NumberOfItems] => 1 [NumberOfPages] => 110 [PackageDimensions] => Array ( [Height] => 0.65 [Length] => 8.60 [Width] => 5.65 [Weight] => 0.58 ) [PackageQuantity] => 1 [PartNumber] => 9780786866021 [ProductGroup] => Book [ProductTypeName] => ABIS_BOOK [PublicationDate] => 2000-03-08 [Publisher] => Hyperion [ReleaseDate] => 2000-03-08 [SmallImage] => Array ( [URL] => http://ecx.images-amazon.com/images/I/51cHo55tbOL._SL75_.jpg [Height] => 75 [Width] => 47 ) [Studio] => Hyperion [Title] => Fish: A Proven Way to Boost Morale and Improve Results ) ) [Relationships] => Array ( ) [SalesRankings] => Array ( [SalesRank] => Array ( [0] => Array ( [ProductCategoryId] => book_display_on_website [Rank] => 4629 ) [1] => Array ( [ProductCategoryId] => 1043856 [Rank] => 2 ) [2] => Array ( [ProductCategoryId] => 2635 [Rank] => 7 ) [3] => Array ( [ProductCategoryId] => 2637 [Rank] => 18 ) ) ) ) [1] ...
I am trying to access the amount part of the array, as this is the price of the object. Eventually, I will need to access the amount of each product and so a loop will likely come into play, but right now i cannot even access one products sales amount.
Here is the code I have been trying
$value = $array->ListMatchingProductsResult->Products->Product[0]->ListPrice->Amount;
print_r($value);
And it is not working. Even calling print_r on $array->ListMatchingProductsResult is not printing an array.
Any help is greatly appreciated!
Thanks,
Matt
You are almost there. Whatever method you are using to convert the XML to a PHP array however, does just that: It creates an associative array of things, not an object. That is why you cannot access it through the ->element operator, but need to use array indexes ['element']
$value = $array['ListMatchingProductsResult']['Products']['Product'][0]['ListPrice']['Amount'];
If you're ever wondering why you're not getting something back, you can successily shorten above expresion until you do. So if a print_r(...) on above expression returns nothing, just remove one square bracket at a time from that print_r until you do get something back. You then know that the last bracket you removed was the culprit.
Array (
[ListMatchingProductsResult] => Array (
[Products] => Array (
[Product] => Array (
[0] => Array (
[Identifiers] => Array (
[MarketplaceASIN] => Array (
[MarketplaceId] => ATVPDKIKX0DER
[ASIN] => 0786866020
)
)
[AttributeSets] => Array (
[ItemAttributes] => Array (
[Author] => Array (
[0] => Stephen C. Lundin
[1] => Harry Paul
[2] => John Christensen
)
[Binding] => Hardcover
[Brand] => Hyperion
[Color] => White
[Creator] => Ken Blanchard
[Edition] => 1
[Feature] => Great product!
[ItemDimensions] => Array (
[Height] => 8.25
[Length] => 5.50
[Width] => 0.00
[Weight] => 0.54
)
[IsAdultProduct] => false
[Label] => Hyperion
[Languages] => Array (
[Language] => Array (
[0] => Array (
[Name] => english
[Type] => Published
)
[1] => Array (
[Name] => english
[Type] => Original Language
)
[2] => Array (
[Name] => english
[Type] => Unknown
)
)
)
[ListPrice] => Array (
[Amount] => 21.00
[CurrencyCode] => USD
)
[Manufacturer] => Hyperion
...
BTW, using <pre>...</pre> is helpful when trying to make sense of print_r() or var_dump().
P.S. You owe me a new space key.
Here is an sdk library that uses the ListMatchingProducts of Amazon MWS. You will be able to get the info in accessing info required.
https://github.com/choomz/amazon-mws-sdk/blob/master/search/src/MarketplaceWebServiceProducts/Samples/ListMatchingProductsSample.php
To show php errors have this set in your php.in
display_errors = On
You can also give this on top of the php script
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
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
)
)
)
$data = file_get_contents("https://graph.facebook.com/246179452202174/posts?access_token=TOKEN");
$data = json_decode($data, true);
print_r(array_values($data));
That's my code. It's simple. I can see the data and when I visit the link, it gives me the same info. So that works perfect. Underneath there's some outputs from the api.
Array ( [0] => Array ( [0] => Array ( [id] => 246179452202174_685970631556385 [from] => Array ( [name] => LGB eSports [category] => Sports Team [id] => 246179452202174 ) [message] => We are back! Sorry that we have been silent! But the silence is over! We will soon update you with some breaking news, stay tuned! Do not move your eyes! You do not want to miss this... [privacy] => Array ( [value] => [description] => [friends] => [allow] => [deny] => ) [type] => status [status_type] => mobile_status_update [created_time] => 2016-05-26T13:12:23+0000 [updated_time] => 2016-05-26T13:12:23+0000 [is_hidden] => [is_expired] => [likes] => Array ( [data] => Array ( [0] => Array ( [id] => 1042109789201130 [name] => Fabio Broggi ) [1] => Array ( [id] => 713442998796859 [name] => Christian Bråten ) [2] => Array ( [id] => 1801480580073327 [name] => Paulo Henrique ) [3] => Array ( [id] => 971217726332439 [name] => Benjamin Holm Davidsen ) ) [paging] => Array ( [cursors] => Array ( [before] => MTA0MjEwOTc4OTIwMTEzMAZDZD [after] => OTcxMjE3NzI2MzMyNDM5 ) ) ) )
When I try to echo $data or maybe $data[1] or something like it, it wont work. Also removing array_values gives me a output of "Array" or "ArrayArray".
So how may I print out the data from the api? It wont work, also; how may I fetch the image? I'd like to print the title of the post, and the image. As a link for a feed at my site.
More response code for link:
Array ( [data] => Array ( [0] => Array ( [id] => 246179452202174_685970631556385 [from] => Array ( [name] => LGB eSports [category] => Sports Team [id] => 246179452202174 ) [message] => We are back! Sorry that we have been silent! But the silence is over! We will soon update you with some breaking news, stay tuned! Do not move your eyes! You do not want to miss this... [privacy] => Array ( [value] => [description] => [friends] => [allow] => [deny] => ) [type] => status [status_type] => mobile_status_update [created_time] => 2016-05-26T13:12:23+0000 [updated_time] => 2016-05-26T13:12:23+0000 [is_hidden] => [is_expired] => [likes] => Array ( [data] => Array ( [0] => Array ( [id] => 1042109789201130 [name] => Fabio Broggi ) [1] => Array ( [id] => 713442998796859 [name] => Christian Bråten ) [2] => Array ( [id] => 1801480580073327 [name] => Paulo Henrique ) [3] => Array ( [id] => 971217726332439 [name] => Benjamin Holm Davidsen ) ) [paging] => Array ( [cursors] => Array ( [before] => MTA0MjEwOTc4OTIwMTEzMAZDZD [after] => OTcxMjE3NzI2MzMyNDM5 ) ) ) ) [1] => Array ( [id] => 246179452202174_680011585485623 [from] => Array ( [name] => Yoyo xno [category] => Musician/Band [id] => 281466768681242 ) [to] => Array ( [data] => Array ( [0] => Array ( [name] => LGB eSports [category] => Sports Team [id] => 246179452202174 ) ) ) [message] => GG - Spotify: https://open.spotify.com/track/7tT6XVWfjtpNF8enpFpZT4 [privacy] => Array ( [value] => [description] => [friends] => [allow] => [deny] => ) [type] => status [status_type] => wall_post [created_time] => 2016-05-12T17:33:49+0000 [updated_time] => 2016-05-12T17:33:49+0000 [is_hidden] => [is_expired] => [likes] => Array ( [data] => Array ( [0] => Array ( [id] => 196458690716329 [name] => Funny memes pics ) ) [paging] => Array ( [cursors] => Array ( [before] => MTk2NDU4NjkwNzE2MzI5 [after] => MTk2NDU4NjkwNzE2MzI5 ) ) ) ) [2] => Array ( [id] => 246179452202174_676411742512274 [from] => Array ( [name] => LGB eSports [category] => Sports Team [id] => 246179452202174 ) [message] => Breaking news! Changes in the team. We are sad to announce that Aurora will part ways with Lgb Female. We wish to thank her for the time she spent with us and we wish her all the best for the future. Here's what she says about this herself: "My time with LGB eSports has come to an end. I am extremely thankful for the opportunity to grow within this team, go to amazing places and meet amazing people. I have learnt so much from this experience and I will never forget all the adventures we've had together! I would like to use this moment of change to look back and sincerely thank all my team-mates for this learning experience, Per Lilliefelth for looking after us, our sponsor Intel for taking care of us and LGB eSports for their immense contribution to helping us grow as an all-female team in Counter-Strike. I am certain I will still remain close to the team and look forward to seeing them at many future events. As for myself I am currently a free agent and look forward to continuing my journey as a competitive CS:GO player for many more years to come. Regards, Aurora Lyngdal" [picture] => https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/13174168_676411742512274_4595019159434717947_n.jpg?oh=dad6bffaf94a2eae60c578d58f7cf8fc&oe=57E7E3F3 [link] => https://www.facebook.com/LGBeSports/photos/a.252900201530099.1073741829.246179452202174/676411742512274/?type=3 [name] => Timeline Photos [icon] => https://www.facebook.com/images/icons/photo.gif [privacy] => Array ( [value] => [description] => [friends] => [allow] => [deny] => ) [type] => photo [status_type] => added_photos [object_id] => 676411742512274 [created_time] => 2016-05-04T15:08:52+0000 [updated_time] => 2016-05-11T20:30:20+0000 [shares] => Array ( [count] => 4 ) [is_hidden] => [is_expired] => [likes] => Array ( [data] => Array ( [0] => Array ( [id] => 1756499731303402 [name] => Antony Giordans ) [1] => Array ( [id] => 196458690716329 [name] => Funny memes pics ) [2] => Array ( [id] => 10205058377778051 [name] => Charmaine Anne D. Better ) [3] => Array ( [id] => 992479757539742 [name] => Yunus Emre Çeker ) [4] => Array ( [id] => 244636029237859 [name] => Roman Hardinger ) [5] => Array ( [id] => 1134092109982746 [name] => Khoa Nguyen ) [6] => Array ( [id] => 525969817592366 [name] => Joseph Turton ) [7] => Array ( [id] => 1152533898100318 [name] => Kristian Sørensen ) [8] => Array ( [id] => 1193252910715325 [name] => Kamil Grochu Groszek ) [9] => Array ( [id] => 1158759100821275 [name] => Ace Kjirkovski ) [10] => Array ( [id] => 10153477966360064 [name]
you must echo this variable
$data[0][0]['message']
Any idea how to access creator with foreach? I receive this as a result from the linkedin groups API and want to iterate through it, after joining the first level with foreach($data as $value) - I am not sure how to iterate through the second and third array to access the values for creator
Array
(
[_total] => 4
[values] => Array
(
[0] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test1
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => hi summary
[title] => hi title
)
[1] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test2
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => summary
[title] => testpost
)
[2] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test3
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => 12312
[title] => linkedinDEV
)
[3] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test4
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => test123
[title] => Discussion Title
)
)
)
best
M
Since 5.5, you can use in this case array_column:
$creators = array_column($data['values'],'creator');
This will create an array of creators:
$creators = array();
foreach($data['values'] as $value) {
$creators[] = $value['creator'];
}
// An array containing the creator information
var_dump($creators);
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.