PHP/JSON parsing - php

Array
(
[0] => Array
(
[faq_id] => 14
[faq_faqcat_id] => 3
[faq_order] => 8
[faq_subject] => 800018
[faq_content] => 800019
[faq_datecreated] => 1213382678
[faq_dateupdated] => 1215547984
[faq_views] => 22
)
[1] => Array
(
[faq_id] => 15
[faq_faqcat_id] => 3
[faq_order] => 9
[faq_subject] => 800020
[faq_content] => 800021
[faq_datecreated] => 1213382698
[faq_dateupdated] => 1215547986
[faq_views] => 13
)
[2] => Array
(
[faq_id] => 16
[faq_faqcat_id] => 3
[faq_order] => 10
[faq_subject] => 800022
[faq_content] => 800023
[faq_datecreated] => 1213382711
[faq_dateupdated] => 1215547988
[faq_views] => 15
)
)
The above data is output of a PHP script. I have to convert this to a JSON object and show on an iPhone. can anyone please tell how?

Take a look at the json_encode and json_decode functions
For the parsing part on iOS you can use the native NSJSONSerialization class.

Dunno about iOS side, but from PHP it's pretty simple
http://php.net/manual/en/function.json-encode.php
echo json_encode($myArray);

Related

How to read and convert a protected object to an associative array in PHP [duplicate]

This question already has answers here:
How to get protected property of object in PHP
(8 answers)
Closed 3 years ago.
I am working with an api which answers the requests with "protected" data object
like this
(
[id:protected] => id:NYhXwGRVDzAAAAAAAAAA62
[name:protected] => 5cf8cdd54328c.EDF
[rev:protected] => 014a0000000150eaacf0
[size:protected] => 25136208
[server_modified:protected] => 2019-06-06T08:25:00Z
[has_explicit_shared_members:protected] =>
[data:protected] => Array
(
[name] => 5cf8cdd54328c.EDF
[path_lower] => /5cf8cdd54328c.edf
[path_display] => /5cf8cdd54328c.EDF
[id] => id:NYhXwGRVDzAAAAAAAA125
[client_modified] => 2019-06-06T08:25:00Z
[server_modified] => 2019-06-06T08:25:00Z
[rev] => 014a0000000150eaacf0
[size] => 25136208
[is_downloadable] => 1
[content_hash] => 86442139304784e3b18d1d46f1b20bc48847
)
)
I have converted the object to array with the following code
$metadata = (array)$file->getMetadata();
Array
(
[*id] => id:NYhXwGRVDzAAAAAA44554
[*name] => 5cf8cdd54328c.EDF
[*rev] => 014a0000000150eaacf0
[*size] => 25136208
[*media_info] =>
[*sharing_info] =>
[*path_display] => /5cf8cdd54328c.EDF
[*client_modified] => 2019-06-06T08:25:00Z
[*server_modified] => 2019-06-06T08:25:00Z
[*data] => Array
(
[name] => 5cf8cdd54328c.EDF
[path_display] => /5cf8cdd54328c.EDF
[id] => id:NYhXwGRVDzAAAAAAA23382
[client_modified] => 2019-06-06T08:25:00Z
[server_modified] => 2019-06-06T08:25:00Z
[rev] => 014a0000000150eaacf0
[size] => 25136208
[is_downloadable] => 1
[content_hash] => 86442139304784e3b18d1d46f1b20bc4884
)
)
But when i try to print the value print_r($metadata['*size']);
Notice: Undefined index: *size in C:\xampp\htdocs\Proyectos\kardion\kardion\sistema\download.php on line 28
I think it will be a very easy answer but I have no idea how to do it
I'm unsure where all those asterisks are coming from. I can't see them documented in any of the PHP ::getMetadata functions. Is this something you wrote yourself? I would suggest trying to remove any *s before attempting to read the index, and I suspect that's what's causing your error. Have you tried just print_r($metadata['size']);?

Access 2nd, 3rd level etc.. From json request using php

I am trying to access a multi-dimensional array using PHP. I can access the first level using -
$response['id']
but having trouble with how the second level is defined so I can do -
$response['first level']['second level']
Here is my json response -
Array
(
[id] => 7181676
[api_request_id] => 20984853
[user] => 8305
[vin] => JTDKN3DU7D1643423
[make] => Toyota
[model_name] => Prius
[model_year] => 2013
[last_updated] => 2019-02-22T01:08:15.628318Z
[recall_count] => 1
[status] => ok
[recalls] => Array
(
[0] => Array
(
[recall_id] => 15753
[recall_last_updated] => 2019-02-22T00:33:07.663232Z
[recall_age] => 0
[nhtsa_id] => 18V684000
[oem_id] => J0V
[name] => HybridSystem
[description] => CollisionRisk
[campaign_type] => nhtsa
[is_remedy_available] => 1
[are_parts_available] => 1
[risk_type] => collision
[risk_rank] => 5
[profit_rank] => 3
[overall_rank] => 5
[labor_difficulty] => 3
[government_id] => 18V684000
[is_reviewed] => 1
[child] => Array
(
)
)
)
)
How would I get lets say -
$response['profit_rank']

Array_diff getting error Array to string conversion php

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.

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

PHP SoapClient converting Array to String

Another SOAP question - I have a large multidimensional array, which echo's out fine when using print_r (eg you can see all of the data). The problem arises when I use
SOAPClient->__soapCall('Function', array('paramaters' => $feedUpload));
This actually returns an xml that looks like this: (using __getLastRequest)
<soap-env:envelope xmlns:ns1="http://www.property24.com/prosol/P24Feed" xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:body>
<ns1:uploadlistings>
<ns1:feedupload>
<ns1:version>1</ns1:version>
<ns1:usertoken>
<ns1:token>3c7b39ea-c10b-451f-95bf-5118d84fb089</ns1:token>
</ns1:usertoken>
<ns1:command>UPLOAD</ns1:command>
<ns1:compress>None</ns1:compress>
<ns1:listings>
<ns1:listing>
<ns1:listingnumber>361000001</ns1:listingnumber>
<ns1:propertycategory>SR</ns1:propertycategory>
<ns1:listingdata>Array</ns1:listingdata>
<ns1:listingtype>A</ns1:listingtype>
</ns1:listing>
</ns1:listings>
</ns1:feedupload>
</ns1:uploadlistings>
</soap-env:body>
</soap-env:envelope>
As you can see, for ListingData it returns "Array". Here is the array schema:
Array
(
[parameters] => Array
(
[FeedUpload] => Array
(
[Version] => 1
[UserToken] => Array
(
[Token] => 5ece25e7-77d9-4dbf-8b8f-e047759ab8f4
)
[Command] => UPLOAD
[Compress] => None
[Listings] => Array
(
[Listing] => Array
(
[PropertyCategory] => SR
[ListingNumber] => 361000001
[ListingType] => A
[ListingData] => Array
(
[MandateDetails] => Array
(
[ListingNumber] => 361000001
[ListingType] => A
[MandateType] => O
[ClosedUserGroup] => C
[MarketCode] => A
[ListPrice] => 111000
[OccupationDate] =>
[OffMarketDate] =>
[OnMarketSince] =>
[ExpiryDate] => 2011-07-13T09:56:14Z
[ListDate] => 2011-07-13T09:51:14Z
[UpdateDate] => 2011-07-13T09:51:14Z
[VirtualTourUrl] =>
[ActualDirections] =>
[ShowHouseDirection] =>
[ViewComments] =>
[InternetComments] => Excellent stand situated on the flood plane with large riverine trees and great mountain views. The estate is situated along the world renowned Blyde River and is 394 ha in extent with only 154 sites on 4000 square metres. The estate has an array of plains game such as antelope, giraffe and wildebeest as well as hippo and crocodile. The riverine flood plain provides great birding opportunities such as the Pels fishing owl. There is a restaurant and clubhouse that serves meals and cocktails and offers
)
[PropertyDetails] => Array
(
[PropertyCategory] => SR
[PropertyType] => SRX
[Status] => ACTV
[Province] => Eastern Cape
[Town] => Aberdeen
[Suburb] => Balvinie
[StreetName] => Test Street
[StreetNumber] => 5
[PostalCode] => 0123
[ErfSize] => 1200
[HouseSize] =>
[Age] =>
[OwnerType] => G
[VATRegistered] => false
[MunicipalRatesAndTaxes] => 0
[MunicipalImprovementsValue] => 0
[MunicipalLandValue] => 0
[MunicipalTotalValue] => 0
[StandNumber] =>
[StandNumberSubdivided] =>
[PortionNumber] =>
[OwnerShipType] =>
)
[ResidentialDetails] => Array
(
[NoOfBathrooms] => 2
[BathroomDescription] =>
[NoOfBedrooms] => 6
[BedroomDescription] =>
[NoOfKitchens] => 2
[KitchenDescription] =>
[NoOfReceptionRooms] => 2
[ReceptionRoomDescription] =>
[NoOfStudies] => 1
[StudiesDescription] =>
[NoOfDomesticBathrooms] => 2
[NoOfDomesticRooms] => 0
[DomesticRoomsDescription] =>
[NoOfGarages] => 0
[GarageDescription] =>
[NoOfOutsideToilets] => 0
[Coverage] => 0
[Pool] => false
[PoolDescription] =>
[Flatlet] =>
[FlatletDescription] =>
[FlatletSize] =>
[EstablishedGarden] =>
[OutBuildingSize] =>
[NoOfCarports] => 0
[CarportsDescription] =>
[ParkingBayNumber] =>
[Parking] =>
[ParkingDescription] =>
[BusinessRights] =>
[HeightRestrictions] =>
[CommonFeatures] =>
[NumberOfShares] =>
[FacingOptions] =>
[KitchenOptions] =>
[FeatureOptions] =>
[SpecialFeatureOptions] =>
[WallOptions] =>
[WindowOptions] =>
[StyleOptions] =>
[TemperatureControlOptions] =>
[SecurityOptions] =>
[RoofOptions] =>
[RoomOptions] =>
[PoolOptions] =>
[BathroomOptions] =>
)
[AgentDetails] => Array
(
[InternetAgentName] => Ricky Duckworth
[InternetAgentPhoneNumber] => 0157931534
[InternetAgentEmailAddress] => ricky#propertylogic.net
[InternetAgentSMSNumber] => 0796057834
[ListingAgentCode] => CN21
[ListingAgencyCode] => CWP021
)
)
)
)
)
)
)
As you can see the array is structured fine. It's like SoapRequest has got to far into an array and stopped. I also get the notice
Notice: Array to string conversion in /var/www/vhosts/propertylogic.net/httpdocs/soap_feed/property24/add_property.php on line 178
Which is the SOAPCall line.
Thanks very much!
EDIT
[EDIT]Ok, basically the SOAP server requested that section to be raw xml, so I had to replace the Array with a String - sort of stupid way of doing things, but the error message now makes sense! (Can't answer my own question).
You'd better generate and use WSDL to create SOAP Client and define complex types there. This way every SOAP type will be converted to PHP types in a natural way (in your example it'll be an array of objects).
Or you can replace array with string as you did already, though it is a dirty magic :)

Categories