json_encode loses some object values in php - php

I have an object $myObject; I'm trying to return php object as json, but it loses some data. This is how $myObject looks:
CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList Object
(
[priceListId:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 32
[amounts:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 1000
[1] => 2000
[2] => 3000
[3] => 4000
[4] => 5000
[5] => 6000
[6] => 7000
)
[amountsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[1000] => 0
[2000] => 1
[3000] => 2
[4000] => 3
[5000] => 4
[6000] => 5
[7000] => 6
)
[periods:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[0] => 10
[1] => 15
[2] => 20
[3] => 25
[4] => 30
)
[periodsKeys:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[10] => 0
[15] => 1
[20] => 2
[25] => 3
[30] => 4
)
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 7000
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => 30
[prices:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => Array
(
[30] => Array
(
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)
)
)
[settings:CreditOnline\Bundle\CreditOnlineBundle\PriceList\PriceList:private] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings Object
(
[mode:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => credits
[preset:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] =>
[implementation:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => matrix
[defaults:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Settings:private] => Array
(
[period] =>
[amount] =>
)
)
)
After json_encode($myObject); new data looks like this (screenshot for better json view):
screenshot of returned json
Why information I wrote below is missing and how to access it?
Missing stuff:
[7000] => CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price Object
(
[period:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 30
[amount:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 7000
[charge:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1580
[interest:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[administrativeFee:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[payment:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 0
[annualPercentageRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 1089.6
[annualInterestRate:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] => 274.62
[schedule:CreditOnline\Bundle\CreditOnlineBundle\PriceList\Price:private] =>
)

The problem is json_encode can not access private properties.
Here are some workarounds you could do:
Convert the properties to be public
You could use a reflection class to convert the properties accessibility before you convert it
Example:
$refObject = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
You could loop through the properties of the object using a Reflection object and call all the getters converting the object into an array structure that could be easily translated
Refelection Class Documentation

Related

PHP - Extract specific property info from Array of Objects

I am working on something in Wordpress and need to parse an array of objects and get some specific property information values.
I believe I am having issues be cause the property name has colons in it:
EX: id:DLM_Download_Version:private
The arrays name is $versions. This is the value of the array when i use print_r:
(
[0] => DLM_Download_Version Object
(
[id:DLM_Download_Version:private] => 208
[author:DLM_Download_Version:private] => 1
[download_id:DLM_Download_Version:private] => 196
[menu_order:DLM_Download_Version:private] => 0
[latest:DLM_Download_Version:private] =>
[date:DLM_Download_Version:private] => DateTime Object
(
[date] => 2022-03-22 12:48:00.000000
[timezone_type] => 3
[timezone] => UTC
)
[version:DLM_Download_Version:private] => 3
[download_count:DLM_Download_Version:private] => 0
[filesize:DLM_Download_Version:private] => 2966739
[md5:DLM_Download_Version:private] =>
[sha1:DLM_Download_Version:private] =>
[sha256:DLM_Download_Version:private] =>
[crc32b:DLM_Download_Version:private] =>
[mirrors:DLM_Download_Version:private] => Array
(
[0] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/STS-SENTIMENT-REPORT-3-21-22.pdf
)
[url:DLM_Download_Version:private] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/STS-SENTIMENT-REPORT-3-21-22.pdf
[filename:DLM_Download_Version:private] => STS-SENTIMENT-REPORT-3-21-22.pdf
[filetype:DLM_Download_Version:private] => pdf
)
[1] => DLM_Download_Version Object
(
[id:DLM_Download_Version:private] => 200
[author:DLM_Download_Version:private] => 1
[download_id:DLM_Download_Version:private] => 196
[menu_order:DLM_Download_Version:private] => 1
[latest:DLM_Download_Version:private] =>
[date:DLM_Download_Version:private] => DateTime Object
(
[date] => 2022-03-22 12:37:00.000000
[timezone_type] => 3
[timezone] => UTC
)
[version:DLM_Download_Version:private] => 2
[download_count:DLM_Download_Version:private] => 2
[filesize:DLM_Download_Version:private] => 3059630
[md5:DLM_Download_Version:private] =>
[sha1:DLM_Download_Version:private] =>
[sha256:DLM_Download_Version:private] =>
[crc32b:DLM_Download_Version:private] =>
[mirrors:DLM_Download_Version:private] => Array
(
[0] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/sts-weekly-sentiment-report-3-14-22.pdf
)
[url:DLM_Download_Version:private] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/sts-weekly-sentiment-report-3-14-22.pdf
[filename:DLM_Download_Version:private] => sts-weekly-sentiment-report-3-14-22.pdf
[filetype:DLM_Download_Version:private] => pdf
)
[2] => DLM_Download_Version Object
(
[id:DLM_Download_Version:private] => 197
[author:DLM_Download_Version:private] => 1
[download_id:DLM_Download_Version:private] => 196
[menu_order:DLM_Download_Version:private] => 2
[latest:DLM_Download_Version:private] =>
[date:DLM_Download_Version:private] => DateTime Object
(
[date] => 2022-03-22 12:35:00.000000
[timezone_type] => 3
[timezone] => UTC
)
[version:DLM_Download_Version:private] => 1
[download_count:DLM_Download_Version:private] => 0
[filesize:DLM_Download_Version:private] => 2648776
[md5:DLM_Download_Version:private] =>
[sha1:DLM_Download_Version:private] =>
[sha256:DLM_Download_Version:private] =>
[crc32b:DLM_Download_Version:private] =>
[mirrors:DLM_Download_Version:private] => Array
(
[0] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/STS-WEEKLY-SENTIMENT-REPORT-3-8-22.pdf
)
[url:DLM_Download_Version:private] => https://wordpress-360386-2306631.cloudwaysapps.com/wp-content/uploads/dlm_uploads/2022/03/STS-WEEKLY-SENTIMENT-REPORT-3-8-22.pdf
[filename:DLM_Download_Version:private] => STS-WEEKLY-SENTIMENT-REPORT-3-8-22.pdf
[filetype:DLM_Download_Version:private] => pdf
)
)
How can I get just the values of id:DLM_Download_Version:private?
I have tried a foreach loop:
foreach ($versions as $version){
echo $version->{'id:DLM_Download_Version:private'}
}
which just outputs nothing.

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']

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;
}

How do I retrieve an item from an PHP Object Array?

I want to retrieve quantities from this array.
invoice Object
(
[data:private] => Array
(
[i_status] => pend
[i_title] => 500 HLCoins , 500 HLCoins x8
[i_member] => 1
[i_items] => Array
(
[0] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 1
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[extra] =>
[opt_id] => 0
[associated] =>
[assocBought] =>
[groupRenewals] => 0
[methods] => Array
(
)
[k] => 0
[_tax] => 0
)
[1] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 8
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[opt_id] => 0
[groupRenewals] => 0
[methods] => Array
(
)
[_tax] => 0
)
)
[i_total] => 0
[i_date] => 1347217384
[i_return_uri] =>
[i_paid] => 0
[i_status_extra] => a:1:{s:4:"type";s:4:"zero";}
[i_discount] => 0
[i_temp] =>
[i_ordersteps] => 0
[i_noreminder] => 1
[i_renewal_ids] => Array
(
)
[i_po] =>
[i_notes] =>
[i_shipaddress] =>
[i_id] => 229
)
[takeAction] => 1
)
I've tried a bunch of codes like $invoice->quantity, $invoice[1]->quantity, $this->$invoice->quantity, but none of them seem to display.
It still does not display at all, I tried to print_r and that is the array it gave me.
All the variables are private which means you cannot access them from outside the object. Check out the class definition for the invoice class. There should be some function to get the quantities from the object, or else you could add such a feature to the class.
The whole point of this is separation of concerns. The class may change in the future and possibly not use the same structure, therefore you should use object functions to access the properties, do not access them directly as variables.
You can read more on this subject in the manual or in a book about object-oriented programming.
Seems like all the data is in a private property. You cannot access it from outside directly.
Read the documentation for the class. It should have some method you can call, like getQuantity(), that'll get you the data. It depends on how the class was written and how it is supposed to be used.

Stackoverflow API getting answers in array PHP

I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.

Categories