arrays - Structuring OOP Php methods and objects when using a JSON API call -
i making application pulls data through json curl. i'm using php , script creates 2 different objects contain curl requests. i've got data in readable format, need divide average first call average second call.
this average of equal relevance each of calls - , i'm new working objects , classes struggling understand how structure in right way. following line of code doesn't work - but, if read on explain i'm trying do.
$yield = object1->calculate_average($list)->average['price']/object2->calculate_average($list)->average['price']; i want code $yield variable in listing class further method display when call $anobject->yield. should access via a) object1, b) object2, or c) it's own object (which seems excessive..as used occasionally). there right way this, or not matter?
my query general (what best approach using objects when object appears relevant options, , possible reference arrays this: calculate_average($list)->average['price']) as specific (how can fix script)
when has come before i've tended regrab data source , fudge it, because it's json call , therefore takes bit longer i've been prompted find better solution...
a simplified version of best effort far below.
i've assumed need use foreach on json outputs:
class listing { //this takes stdclass object json , prepares served public function output_list($data) { $price = "0"; $vals = "0"; $list = array(); foreach ($data->listing $item) { //calculate average price $price = $price + $item->price; $vals = $vals + 1; //display information each item $list[$vals][] = "price: £" . $item->price . " , various data"; $list[$vals][] = ...; } return $list; } // function calculates equations on data read above public function calculate_average($list) { $average = array(); $total_price = array_column($list, '1'); //find total sum of list[?][1] = price $vals = count($list); //count number of values in list $average['denominator'] = $vals; $average['week'] = $total_price / $average['denominator']; //and number of other calculations within array... return $average; } } i want call these using following code:
$object1 = new listing(); $list1 = $object1->output_list($response); ////output formatted data print_r($list1); $average = $object1->calculate_average($list); $object2 = new listing(); $list2 = $object2->output_list($response); ////output formatted data print_r($list2); $average = $object2->calculate_average($list); the other thing $total_price = array_column($list,'1') needs me have php 5.5 - don't have, need find alternative - , makes me question whether array approach right 1 in first place. [i need sum every [?][1] reference in multi-dimensional array i've made].
if you're able i'd grateful - i've been trying head around objects , classes weeks!
Comments
Post a Comment