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;
Related
I have an array below. What i need to do is unset one array inside "Urunler" than updating a new array. Very crucial one is how can push new array by keeping same key value which is same deleted one.
stdClass Object
(
[Urun] => Array
(
[0] => stdClass Object
(
[Id] => 1384
[Urun_kodu] => UKy74GhoD1LZ
[Urun_adi] => Bizim Ayçiçek Yağı Teneke 5 Lt
[Urun_resim] => uploads/urunler_v/UKy74GhoD1LZ/637b4-bizim-aycicek-yagi-tenekelxwbmlgpdh.jpg
[Esas_tutar] => 27.00
[Esas_tutar_kdvsiz] => 25.00
[Kdv_tutar] => 2.00
[Kdv_tutar_adetli] => 6.00
[Adetli_tutar] => 81.00
[Adetli_tutar_kdvsiz] => 75.00
[Urun_adeti] => 3
[Urun_kuru] => TRY
[Urun_ds] => 100
)
[1] => stdClass Object
(
[Id] => 4518
[Urun_kodu] => UK6FfrWzDPLE
[Urun_adi] => Besler Ton Balığı 2x160 Gr
[Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
[Esas_tutar] => 10.80
[Esas_tutar_kdvsiz] => 10.00
[Kdv_tutar] => 0.80
[Kdv_tutar_adetli] => 2.40
[Adetli_tutar] => 32.40
[Adetli_tutar_kdvsiz] => 30.00
[Urun_adeti] => 3
[Urun_kuru] => TRY
[Urun_ds] => 32
)
[2] => stdClass Object
(
[Id] => 4518
[Urun_kodu] => UK6FfrWzDPLE
[Urun_adi] => Besler Ton Balığı 2x160 Gr
[Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
[Esas_tutar] => 10.80
[Esas_tutar_kdvsiz] => 10.00
[Kdv_tutar] => 0.80
[Kdv_tutar_adetli] => 2.40
[Adetli_tutar] => 32.40
[Adetli_tutar_kdvsiz] => 30.00
[Urun_adeti] => 3
[Urun_kuru] => TRY
[Urun_ds] => 32
)
)
)
Below, you can see my steps when pushing new array
$Urun = $SepetBilgisi->Urun;
$MevcutUrunSayisi=count($Urun);
$YeniUrun=[];
foreach($Urun as $Key => $Value)
{
if($Value->Id== $UrunId){ // My target is $UrunId=4518 that means $Urun[Urun][1] one
unset($Urun[$Key]);
if(count($Urun)< $MevcutUrunSayisi){
//Şimdi Yeni Array Buraya Ekleyelim
$YeniUrun[$Key]=[
"Id"=> $Value->Id,
"Urun_kodu" => $Value->Urun_kodu,
"Urun_resim" => $Value->Urun_resim,
"Esas_tutar" => $Value->Esas_tutar,
"Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
"Kdv_tutar" => $Value->Kdv_tutar,
"Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
"Adetli_tutar" => $Value->Adetli_tutar,
"Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
"Urun_adeti" => $YeniAdet,
"Urun_kuru" => $Value->Urun_kuru,
"Urun_ds" => $Value->Urun_ds
];
array_push($Urun , $YeniUrun);
}else{
return false;
}
}
}
Using 'array_push' only put new array end of main array as you know.
You want to replace the key, not push to the end of the array:
$Urun = $SepetBilgisi->Urun;
$MevcutUrunSayisi=count($Urun);
$YeniUrun=[];
foreach($Urun as $Key => $Value)
{
if($Value->Id== $UrunId){ // My target is $UrunId=4518 that means $Urun[Urun][1] one
if(count($Urun)< $MevcutUrunSayisi){
//Şimdi Yeni Array Buraya Ekleyelim
$replace=[
"Id"=> $Value->Id,
"Urun_kodu" => $Value->Urun_kodu,
"Urun_resim" => $Value->Urun_resim,
"Esas_tutar" => $Value->Esas_tutar,
"Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
"Kdv_tutar" => $Value->Kdv_tutar,
"Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
"Adetli_tutar" => $Value->Adetli_tutar,
"Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
"Urun_adeti" => $YeniAdet,
"Urun_kuru" => $Value->Urun_kuru,
"Urun_ds" => $Value->Urun_ds
];
$Urun[$Key] = $replace;
}else{
return false;
}
}
}
i have this array:
Array
(
[0] => stdClass Object
(
[MarketCurrency] => LTC
[BaseCurrency] => BTC
[MarketCurrencyLong] => Litecoin
[BaseCurrencyLong] => Bitcoin
[MinTradeSize] => 0.03039514
[MarketName] => BTC-LTC
[IsActive] => 1
[IsRestricted] =>
[Created] => 2014-02-13T00:00:00
[Notice] =>
[IsSponsored] =>
[LogoUrl] => https://bittrexblobstorage.blob.core.windows.net/public/6defbc41-582d-47a6-bb2e-d0fa88663524.png
)
[1] => stdClass Object
(
[MarketCurrency] => DOGE
[BaseCurrency] => BTC
[MarketCurrencyLong] => Dogecoin
[BaseCurrencyLong] => Bitcoin
[MinTradeSize] => 462.96296296
[MarketName] => BTC-DOGE
[IsActive] => 1
[IsRestricted] =>
[Created] => 2014-02-13T00:00:00
[Notice] =>
[IsSponsored] =>
[LogoUrl] => https://bittrexblobstorage.blob.core.windows.net/public/a2b8eaee-2905-4478-a7a0-246f212c64c6.png
)
}
I would get the "MarketCurrency" data and "BaseCurrency" data. But I don't know how to do.
How can I do this?
I need your help.
You can do it with simple foreach() to grab the objects.
foreach($data as $obj){
echo "MarketCurrency = $obj->MarketCurrency and BaseCurrency = $obj->BaseCurrency".PHP_EOL;
}
i want array_diff using this code i am also getting output but same time error occur
"Array to string conversion"
I am using codeigniter, i am getting post value in second array(listingdata) with method $this->input->post(); , but my first array getting some dynamic key and value then this two array diff give me output but some time getting error.
Please Help me
Any solution always welcome.
if(isset($_POST)){
foreach($_POST as $key => $value) {
$arr[$key] = $value; // making array
}
}
$result = array_diff($arr,$listingdata);
print_r($result);
print_r($arr);
print_r($listingdata);
My $arr array
Array
(
[itemTitle] => fdafdas
[subtitle] => fadsfdas
[quantity] => 12
[itemDescription] => fdas
[hide_ebay_id] => 89
[ebay_user] => Array
(
[0] =>
)
[ebay_category] => 2984
[e_sub_cat] => 20433
[e_second_child_sub_cat] => 117027
[e_third_child_sub_cat] =>
[ebay_upc] => 31231241341
[Brand] => Unbranded
[MPN] => Does_Not_Apply
[Model] => fsdf
[Country/Region_of_Manufacture] => Unknown
[listingType] => FixedPriceItem
[listingduration] => Days_5
[buy_it_now_price] => 20.00
[shippingtype] => Flat
[fshippingservice] => USPSPriorityFlatRateBox
[shippingservicecost] => 2.0
[shippingsac] => 3.0
[internationalhc] =>
[paypalemailaddress] => sam#jaff.in
[dispatchtimemax] => 3
[location] => CA
[ebaycountry] =>
[ebay_paypalemail] =>
[ReturnsAccepted] => ReturnsAccepted
[returnswithin] => Days_14
[refundoption] => MoneyBack
[shippingcostpaidbyoption] => Seller
[policydescription] => wqdewvfdgbfdggrbf
)
This is my another Array
Array
(
[itemTitle] => fdafdas
[subTitle] => fadsfdas
[categoryId] => 117027
[itemDescription] => fdas
[listingType] => FixedPriceItem
[listingDuration] => Days_5
[startPrice] =>
[buyItNowPrice] => 20.00
[quantity] => 12
[upc] => 31231241341
[paypalEmailAddress] => sam#jaff.in
[returnWithin] => Days_14
[RefundOption] => MoneyBack
[ShippingCostPaidByOption] => Seller
[returnsAccepted] => ReturnsAccepted
[shippingType] => Flat
[cshippingService] =>
[fshippingService] => USPSPriorityFlatRateBox
[dcPostalcode] =>
[ShippingServiceCost] => 2.0
[dshippingPackage] =>
[shippingHandlingcost] =>
[shippingServiceAdditionalCost] => 3.0
[currency] => USD
[country] =>
[location] => CA
[dispatchTimeMax] => 3
[pictureUrl] => Array
(
[0] => http://jaftech.in/ashprey/uploads/69.jpg
)
[policyDescription] => wqdewvfdgbfdggrbf
[internationalShipping] =>
[internationalShippingType] =>
[internationalShippingServiceCost] =>
[internationalshippingServiceAdditionalCost] =>
[cinternationalshippingService] =>
[finternationalshippingService] =>
[internationalShipToLocation] =>
[internationaloriginatingPostalCode] =>
[internationalshippingHandlingcost] =>
[ishippingPackage] => PackageThickEnvelope
[pid] => 89
)
This is because array_diff compares values after typecasting both compared values to string (see documentation notes).
Both of your arrays contain another array (ebay_user and second pictureUrl).
See this answer for recursive array_diff, which should work in your case.
Cleeng_Entity_Collection Object
(
[entityType:protected] => Cleeng_Entity_SubscriptionOffer
[items:protected] => Array
(
[0] => Cleeng_Entity_SubscriptionOffer Object
(
[id:protected] => S955494970_US
[publisherEmail:protected] => vidya+mtc#ooyala.com
[url:protected] =>
[title:protected] => Annual subscription
[description:protected] =>
[period:protected] => year
[price:protected] => 49.99
[applicableTaxRate:protected] => 0
[currency:protected] => USD
[accessToTags:protected] => Array
(
[0] => d962607d3d4c4e3c98a343c7bcb64027
)
[active:protected] => 1
[createdAt:protected] => 1473681112
[updatedAt:protected] => 1473858745
[geoRestrictionEnabled:protected] =>
[geoRestrictionType:protected] =>
[geoRestrictionCountries:protected] => Array
(
)
[pending:protected] =>
[country] => US
[socialCommissionRate] => 0
[averageRating] => 4
[contentType] =>
[freePeriods] => 0
[freeDays] => 0
[expiresAt] =>
)
)
[totalItemCount:protected] => 5
[pending:protected] =>
)
All you need to do is just convert the Collection to a Regular Array and then json_encode() the Result like so:
<?php
$entityCollection = "???"; // THIS IS THE DATA FROM Cleeng_Entity_Collection Object
$entityArray = $entityCollection->toArray();
$entityJSON = json_encode($entityArray);
I am using a wrapper that makes it very simple to grab a search term and convert it into an array.
I am having trouble parsing this array. How do I create a foreach() loop to get the values from this array?
This is the simple function that is grabbing the search term and converting to an array. The print_r() simply shows me what is being returned.:
require_once (get_template_directory() . '/Classes/itunes.php');
function itunesSearch() {
$search_term = $_GET['s'];
$results = iTunes::search($search_term, array(
'country' => 'US'
))->results;
print_r($results);
}
For example, let's say I search for Adele. Here is the array that is being returned:
Array ( [0] => stdClass Object ( [wrapperType] => track [kind] => song [artistId] => 262836961 [collectionId] => 1051394208 [trackId] => 1051394215 [artistName] => Adele [collectionName] => 25 [trackName] => Hello [collectionCensoredName] => 25 [trackCensoredName] => Hello [artistViewUrl] => https://itunes.apple.com/us/artist/adele/id262836961?uo=4 [collectionViewUrl] => https://itunes.apple.com/us/album/hello/id1051394208?i=1051394215&uo=4 [trackViewUrl] => https://itunes.apple.com/us/album/hello/id1051394208?i=1051394215&uo=4 [previewUrl] => http://a1912.phobos.apple.com/us/r1000/170/Music6/v4/68/34/f1/6834f1f8-8fdb-4247-492a-c0caea580082/mzaf_3920281300599106672.plus.aac.p.m4a [artworkUrl30] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/30x30bb.jpg [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/60x60bb.jpg [artworkUrl100] => http://is5.mzstatic.com/image/thumb/Music6/v4/8c/91/5d/8c915d9b-d9e4-f735-1b91-81ca1b6e6312/source/100x100bb.jpg [collectionPrice] => 10.99 [trackPrice] => 1.29 [releaseDate] => 2015-11-20T08:00:00Z [collectionExplicitness] => notExplicit [trackExplicitness] => notExplicit [discCount] => 1 [discNumber] => 1 [trackCount] => 11 [trackNumber] => 1 [trackTimeMillis] => 295502 [country] => USA [currency] => USD [primaryGenreName] => Pop [radioStationUrl] => https://itunes.apple.com/station/idra.1051394215 [isStreamable] => )
[1] => stdClass Object ( [wrapperType] => track [kind] => song [artistId] => 262836961 [collectionId] => 420075073 [trackId] => 420075084 [artistName] => Adele [collectionName] => 21 [trackName] => Rolling in the Deep [collectionCensoredName] => 21 [trackCensoredName] => Rolling in the Deep [artistViewUrl] => https://itunes.apple.com/us/artist/adele/id262836961?uo=4 [collectionViewUrl] => https://itunes.apple.com/us/album/rolling-in-the-deep/id420075073?i=420075084&uo=4 [trackViewUrl] => https://itunes.apple.com/us/album/rolling-in-the-deep/id420075073?i=420075084&uo=4 [previewUrl] => http://a818.phobos.apple.com/us/r1000/115/Music/3d/fd/74/mzm.dqadcdcf.aac.p.m4a [artworkUrl30] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/30x30bb.jpg [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/60x60bb.jpg [artworkUrl100] => http://is5.mzstatic.com/image/thumb/Music/v4/cf/7e/47/cf7e47a8-bb18-9156-43d0-7591d0e0855e/source/100x100bb.jpg [collectionPrice] => 10.99 [trackPrice] => 1.29 [releaseDate] => 2011-02-22T08:00:00Z [collectionExplicitness] => notExplicit [trackExplicitness] => notExplicit [discCount] => 1 [discNumber] => 1 [trackCount] => 12 [trackNumber] => 1 [trackTimeMillis] => 228293 [country] => USA [currency] => USD [primaryGenreName] => Pop [radioStationUrl] => https://itunes.apple.com/station/idra.420075084 [isStreamable] => 1 ) ...
This is what I've tried, and several variations of this:
$results_thing = $results['stdClass']['Object'];
foreach ($results_thing as $result) {
echo $result['wrapperType'];
I am getting the error:
Warning: Invalid argument supplied for foreach()
Say that the $results holds the array you given above. Then the code for getting 'wrapperType'...
foreach($results as $result) {
$wrapper_type = $result->wrapperType;
}