So i was trying to get "title" and "Artist->name" from all the indexes
and i tried many times even used foreach but i am still learning curl and can only get it for the first index or a specific index here is the table
(
[data] => Array
(
[0] => Array
(
[id] => 2298089
[readable] => 1
[title] => Broken Strings
[title_short] => Broken Strings
[title_version] =>
[link] => https://www.deezer.com/track/2298089
[duration] => 250
[rank] => 749501
[explicit_lyrics] =>
[explicit_content_lyrics] => 0
[explicit_content_cover] => 0
[preview] => https://cdns-preview-1.dzcdn.net/stream/c-140e953bb38254bc8db4fe4dc97dd689-8.mp3
[md5_image] => 71698262cce4bb1c0e3d25e0707ed092
[artist] => Array
(
[id] => 4523
[name] => James Morrison
[link] => https://www.deezer.com/artist/4523
[picture] => https://api.deezer.com/artist/4523/image
[picture_small] => https://e-cdns-images.dzcdn.net/images/artist/794afe1359f598a28dc12c5496fefc2e/56x56-000000-80-0-0.jpg
[picture_medium] => https://e-cdns-images.dzcdn.net/images/artist/794afe1359f598a28dc12c5496fefc2e/250x250-000000-80-0-0.jpg
[picture_big] => https://e-cdns-images.dzcdn.net/images/artist/794afe1359f598a28dc12c5496fefc2e/500x500-000000-80-0-0.jpg
[picture_xl] => https://e-cdns-images.dzcdn.net/images/artist/794afe1359f598a28dc12c5496fefc2e/1000x1000-000000-80-0-0.jpg
[tracklist] => https://api.deezer.com/artist/4523/top?limit=50
[type] => artist
)
[album] => Array
(
[id] => 229099
[title] => Songs For You, Truths For Me (International Exclusive Bundle)
[cover] => https://api.deezer.com/album/229099/image
[cover_small] => https://e-cdns-images.dzcdn.net/images/cover/71698262cce4bb1c0e3d25e0707ed092/56x56-000000-80-0-0.jpg
[cover_medium] => https://e-cdns-images.dzcdn.net/images/cover/71698262cce4bb1c0e3d25e0707ed092/250x250-000000-80-0-0.jpg
[cover_big] => https://e-cdns-images.dzcdn.net/images/cover/71698262cce4bb1c0e3d25e0707ed092/500x500-000000-80-0-0.jpg
[cover_xl] => https://e-cdns-images.dzcdn.net/images/cover/71698262cce4bb1c0e3d25e0707ed092/1000x1000-000000-80-0-0.jpg
[md5_image] => 71698262cce4bb1c0e3d25e0707ed092
[tracklist] => https://api.deezer.com/album/229099/tracks
[type] => album
)
[type] => track
)
[1] => Array
(
[id] => 1196110412
etc.., and here is the code
$ch = curl_init();
$url = "https://api.deezer.com/search?q=broken%20strings";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)){
echo $e;
}else{
$decoded = json_decode($resp,true);
print_r($decoded);
}
curl_close($ch);
this posts all of array
$decoded['data'] will contain an array with all your records, so you want to foreach over that:
foreach ($decoded['data'] as $record) {
On each iteration of that loop, $record will be the subarray for each individual record. So on the first iteration, $record will be:
Array(
[id] => 2298089
[readable] => 1
[title] => Broken Strings
[title_short] => Broken Strings
[title_version] =>
[link] => https://www.deezer.com/track/2298089
[duration] => 250
[rank] => 749501
...
Then you can reference each field in that array like $record['id'] or $record['link']. To "drill down" into multi-dimensional arrays, just stack consecutive [] references, like $record['album']['id'] or $record['artist']['link'].
All together:
foreach ($decoded['data'] as $record) {
printf("Title: %s\n", $record['title']);
printf("Artist: %s\n\n", $record['artist']['name']);
}
Related
I'm getting data from an API using the following:
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "Space-X", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$response = get_web_page("https://api.spacexdata.com/v3/launches/latest?pretty=true");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
With the returned data I'm trying to get specific elements from the array. For example the flight number is easy enough by using:
$flight_number = $resArr->flight_number;
echo $flight_number;
But doing something like the following to get the serial number doesn't work. Where am I going wrong?
$core_serial = $resArr->rocket->first_stage->cores->0->core_serial;
echo $core_serial;
Here's the output of the API:
stdClass Object
(
[flight_number] => 78
[mission_name] => CRS-17
[mission_id] => Array
(
[0] => EE86F74
)
[launch_year] => 2019
[launch_date_unix] => 1556952480
[launch_date_utc] => 2019-05-04T06:48:00.000Z
[launch_date_local] => 2019-05-04T02:48:00-04:00
[is_tentative] =>
[tentative_max_precision] => hour
[tbd] =>
[launch_window] => 0
[rocket] => stdClass Object
(
[rocket_id] => falcon9
[rocket_name] => Falcon 9
[rocket_type] => FT
[first_stage] => stdClass Object
(
[cores] => Array
(
[0] => stdClass Object
(
[core_serial] => B1056
[flight] => 0
[block] => 5
[gridfins] => 1
[legs] => 1
[reused] =>
[land_success] => 1
[landing_intent] => 1
[landing_type] => ASDS
[landing_vehicle] => OCISLY
)
)
)
[second_stage] => stdClass Object
(
[block] => 5
[payloads] => Array
(
[0] => stdClass Object
(
[payload_id] => CRS-17
[norad_id] => Array
(
[0] => 44222
)
[cap_serial] => C113
[reused] => 1
[customers] => Array
(
[0] => NASA (CRS)
)
[nationality] => United States
[manufacturer] => SpaceX
[payload_type] => Dragon 1.1
[payload_mass_kg] => 2482
[payload_mass_lbs] => 5472
[orbit] => ISS
[orbit_params] => stdClass Object
(
[reference_system] => geocentric
[regime] => low-earth
[longitude] =>
[semi_major_axis_km] => 6787.07
[eccentricity] => 0.0001369
[periapsis_km] => 408.006
[apoapsis_km] => 409.865
[inclination_deg] => 51.6417
[period_min] => 92.743
[lifespan_years] =>
[epoch] => 2019-05-14T13:40:22.000Z
[mean_motion] => 15.5267006
[raan] => 168.2377
[arg_of_pericenter] => 352.6849
[mean_anomaly] => 127.392
)
[mass_returned_kg] =>
[mass_returned_lbs] =>
[flight_time_sec] =>
[cargo_manifest] => https://www.nasa.gov/sites/default/files/atoms/files/spacex_crs-17_mission_overview.pdf
)
)
)
[fairings] =>
)
[ships] => Array
(
[0] => OCISLY
[1] => Hollywood
[2] => GOQUEST
)
[telemetry] => stdClass Object
(
[flight_club] => https://www.flightclub.io/result/2d?code=CR17
)
[launch_site] => stdClass Object
(
[site_id] => ccafs_slc_40
[site_name] => CCAFS SLC 40
[site_name_long] => Cape Canaveral Air Force Station Space Launch Complex 40
)
[launch_success] => 1
[links] => stdClass Object
(
[mission_patch] => https://images2.imgbox.com/12/47/6uim8L1a_o.png
[mission_patch_small] => https://images2.imgbox.com/fc/58/9UErD3ut_o.png
[reddit_campaign] => https://new.reddit.com/r/spacex/comments/bd2l28/crs17_launch_campaign_thread/
[reddit_launch] => https://www.reddit.com/r/spacex/comments/bjsn0v/rspacex_crs17_official_launch_discussion_updates
[reddit_recovery] => https://www.reddit.com/r/spacex/comments/bjy7p5/rspacex_crs17_recovery_discussion_updates_thread
[reddit_media] => https://www.reddit.com/r/spacex/comments/bkc4d5/rspacex_crs17_media_thread_videos_images_gifs
[presskit] => https://www.spacex.com/sites/spacex/files/crs-17_press_kit.pdf
[article_link] => https://spaceflightnow.com/2019/05/04/spacex-launches-space-station-resupply-mission-lands-rocket-on-drone-ship/
[wikipedia] => https://en.wikipedia.org/wiki/SpaceX_CRS-17
[video_link] => https://youtu.be/AQFhX5TvP0M
[youtube_id] => AQFhX5TvP0M
[flickr_images] => Array
(
[0] => https://live.staticflickr.com/65535/46856594435_206c773b5a_o.jpg
[1] => https://live.staticflickr.com/65535/47720639872_284e49381d_o.jpg
[2] => https://live.staticflickr.com/65535/46856594755_88f1b22e50_o.jpg
[3] => https://live.staticflickr.com/65535/47720639542_1b7c1a71b0_o.jpg
[4] => https://live.staticflickr.com/65535/47720639732_e04b2a9ed7_o.jpg
[5] => https://live.staticflickr.com/65535/32829382467_087d024428_o.jpg
)
)
[details] => SpaceX's 17th Commercial Resupply Services mission for NASA out of a total of 20 contracted flights, this mission brings essential supplies to the International Space Station using SpaceX's reusable Dragon 1 spacecraft. The external payloads for this mission include Orbital Carbon Observatory 3 and Space Test Program-Houston 6. The Falcon 9 launches from SLC-40 at Cape Canaveral AFS. The booster was expected to land at LZ-1, however, due to the ongoing investigation and clean-up following the Crew Dragon testing incident, it is likely to land on OCISLY instead.
[upcoming] =>
[static_fire_date_utc] => 2019-04-27T07:23:00.000Z
[static_fire_date_unix] => 1556349780
[timeline] => stdClass Object
(
[webcast_liftoff] => 900
[go_for_prop_loading] => -2280
[rp1_loading] => -2100
[stage1_lox_loading] => -2100
[stage2_lox_loading] => -960
[engine_chill] => -420
[prelaunch_checks] => -60
[propellant_pressurization] => -60
[go_for_launch] => -45
[ignition] => -3
[liftoff] => 0
[maxq] => 72
[meco] => 137
[stage_sep] => 141
[second_stage_ignition] => 148
[first_stage_boostback_burn] => 154
[first_stage_entry_burn] => 399
[first_stage_landing] => 507
[seco-1] => 519
[dragon_separation] => 578
[dragon_solar_deploy] => 728
[dragon_bay_door_deploy] => 8340
)
)
You have an array down there in the mix, specifically cores
See how it is annotated on the dump [cores] => Array rather than, for example [rocket] => stdClass Object
so
$core_serial = $resArr->rocket->first_stage->cores[0]->core_serial;
I am using php curl to get account and transaction data from the plaid api. I'd like to see it in a nice format so I can go about creating loops to save the information into a database. The decoded json output, when printed with print_r, is returned like this:
array ( [accounts] => Array ( [0] => Array ( [_id] => QPO8Jo8vdDHMepg41PBwckXm4KdK1yUdmXOwK [_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA [_user] => eJXpMzpR65FP4RYno6rzuA7OZjd9n3Hna0RYa [balance] => Array ( [available] => 1203.42 [current] => 1274.93 ) [institution_type] => fake_institution [meta] => Array ( [name] => Plaid Savings [number] => 9606 ) [subtype] => savings [type] => depository ) [1] => Array ( [_id] => nban4wnPKEtnmEpaKzbYFYQvA7D7pnCaeDBMy [_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA...
I'd like to get it looking like this:
Array (
[accounts] => Array (
[0] => Array (
[_id] => QPO8Jo8vdDHMepg41PBwckXm4KdK1yUdmXOwK
[_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA
[_user] => eJXpMzpR65FP4RYno6rzuA7OZjd9n3Hna0RYa
[balance] => Array (
[available] => 1203.42
[current] => 1274.93 )
[institution_type] => fake_institution
[meta] => Array (
[name] => Plaid Savings
[number] => 9606 )
[subtype] => savings
[type] => depository )
[1] => Array (
[_id] => nban4wnPKEtnmEpaKzbYFYQvA7D7pnCaeDBMy
[_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA
`
For reference, here is the code to get the response:
$data = array(
"client_id"=>"test_id",
"secret"=>"test_secret",
"access_token"=>"test_chase"
);
$string = http_build_query($data);
//initialize session
$ch=curl_init("https://tartan.plaid.com/connect/get");
//set options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute session
$accountData = json_decode(curl_exec($ch), true);
print_r($accountData);
//close session
curl_close($ch);
Any thoughts other than loops?
I want to fetch player fields:
e.g id,name,tag,plat etc
I have this type of data:
stdClass Object
(
[player] => stdClass Object
(
[id] => 179203896
[game] => bf4
[plat] => pc
[name] => HeLLTiMe
[tag] => DK
[dateCheck] => 1391437377733
[dateUpdate] => 1391437377733
[dateCreate] => 1386696304438
[lastDay] => 20140117
[country] =>
[countryName] =>
[rank] => stdClass Object
(
[nr] => 73
[imgLarge] => bf4/ranks/r73.png
[img] => r73
[name] => Chief Warrant Officer Five III
[needed] => 4920000
[next] => stdClass Object
(
[nr] => 74
[img] => r74
[name] => Chief Warrant Officer Five IV
[needed] => 5030000
[curr] => 5022060
[relNeeded] => 110000
[relCurr] => 102060
[relProg] => 92.781818181818
)
)
[score] => 5025100
[timePlayed] => 862027
[uId] => 2832659368608119092
[uName] => HeLLTiMe
[uGava] => 0b8b00021ebfb32414e5a6051c2c9a40
[udCreate] => 1328606863000
[blPlayer] => http://battlelog.battlefield.com/bf4/soldier/HeLLTiMe/stats/179203896/pc/
[blUser] => http://battlelog.battlefield.com/bf4/user/HeLLTiMe/
[editable] =>
[viewable] => 1
[adminable] =>
[linked] =>
)
[stats] => stdClass Object
(
[reset] => stdClass Object
(
[lastReset] => 0
[score] => 0
[timePlayed] => 0
[timePlayedSinceLastReset] => 0
[kills] => 0
[deaths] => 0
[shotsFired] => 0
[shotsHit] => 0
[numLosses] => 0
[numWins] => 0
)
How can I fetch this data?
Here is my code:
<?php
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
$data = json_decode($json);
echo "<pre>";
print_r($data);
?>
to get the name you should do this:
echo $data->player->name;
You need this because you have a stdClass Object
You can also change the out to just a array, you have to change this:
$data = json_decode($json);
to this:
$data = json_decode($json, true);
When you make this chagne you can get the value by this:
echo $data['player']['name'];
Edit
Below you can see the example, this works for me with no error.
$url = "http://api.bf4stats.com/api/playerInfo?plat=pc&name=HeLLTiMe";
$json = file_get_contents($url);
echo 'Using stdClass Object option<br>';
$data = json_decode($json);
echo $data->player->name;
echo '<br><br>Using Array option<br>';
$data = json_decode($json, true);
echo $data['player']['name'];
exit;
$result = array();
$result['name'] = $data->Player->name
var_dump($result);
Not sure what do you mean by fetch the data as already fetched it but if you ask how to access the fields you can do it like this.
print_r($data->player->name);
I have the following array structure, this is the array passed in to $response
Array
(
[inbox] => Array
(
[0] => Array
(
[location] => 3
[ID] => 8ba84195fe79a89af1a4b5bd8c280621
[smsc_number] => +44******
[sent] => 2013-02-25 14:57:20
[coding] => Default GSM alphabet (no compression)
[remote_number] => +447****
[status] => Read
[body] => Yeppp
)
)
[outbox] => Array
(
[0] => Array
(
[location] => 2
[ID] => d22c4368fadd64e98fab64acb6b8fa34
[reference_number] => 1
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => *****
[status] => Sent
[body] => Test
)
[1] => Array
(
[location] => 0
[ID] => f0c05e8dd2578d16d73bf5dbcf2ec3e6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
[2] => Array
(
[location] => 1
[ID] => d7537acb1b3994ecc11369bac46c4bb6
[class] => 1
[coding] => Default GSM alphabet (no compression)
[remote_number] => 0****3
[status] => UnSent
[body] => fdgg ddfgfdg fd
)
)
)
I'm only interested in the body of the inbox array. I thought I could just do two loops to get this, or just do $response[0] but it doesn't seem to work. Heres what I have:
$response = $sms->Get();
foreach ($response[0] as $value) {
foreach ($response as $value1) {
echo($value1['body']);
}
}
I'm obviously doing something very stupid - Any help would be really appreciated
Try this
foreach ($response['inbox'] as $inb) {
echo($inb['body']); }
I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!
You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}