Filtering an Array - php

I'm working on a website that displays properties. I have a huge XML feed in which I put into an array.
function search_results($department = '', $post_code = '', $min_price = '', $max_price = '', $type = '', $bedrooms = '') {
foreach($this->xml->property as $property) {
if($property->department == $department) {
$this->properties[] = $property;
}
}
$this->filter_results();
}
this first filters the XML based on the department such as 'For Sale' or 'To Rent'. I want to now be able to search this array based on the variables I pass though the function. For example:
if($this->properties->regionID == $post_code) {
$this->properties[] = $property;
}
But this doesn't work. This will be in a class called Results. How will I go about searching the array. I had a look at using array_filter(); but I couldn't get it working it would return Array() when I print_r it.
Does anyone know how to search/filter an array?
This is what the array looks like when I print_r:
Array ( [0] => SimpleXMLElement Object ( [propertyID] => 1 [branchID] => 1 [clientName] => Name [branchName] => Branch [department] => Lettings [referenceNumber] => 1 [addressName] => 4 [addressNumber] => SimpleXMLElement Object ( ) [addressStreet] => address [address2] => address2 [address3] => address3 [address4] => SimpleXMLElement Object ( ) [addressPostcode] => postcode [country] => postcode [displayAddress] => address [propertyBedrooms] => 1 [propertyBathrooms] => 1 [propertyEnsuites] => 0 [propertyReceptionRooms] => 1 [propertyKitchens] => 1 [displayPropertyType] => Flat/Apartment [propertyType] => 2 [propertyStyle] => 16 [propertyAge] => 0 [floorArea] => 0.00 [floorAreaUnits] => sq ft [propertyFeature1] => Converted School House [propertyFeature2] => City Centre Location [propertyFeature3] => Modern Fittings [propertyFeature4] => SimpleXMLElement Object ( ) [propertyFeature5] => SimpleXMLElement Object ( ) [propertyFeature6] => SimpleXMLElement Object ( ) [propertyFeature7] => SimpleXMLElement Object ( ) [propertyFeature8] => SimpleXMLElement Object ( ) [propertyFeature9] => SimpleXMLElement Object ( ) [propertyFeature10] => SimpleXMLElement Object ( ) [rent] => 525 [rentFrequency] => 1 [toLetPOA] => 0 [studentProperty] => SimpleXMLElement Object ( ) [availability] => 2 [mainSummary] => summary. [fullDescription] => SimpleXMLElement Object ( ) [dateLastModified] => 2014-05-02 [featuredProperty] => 0 [regionID] => 27 [latitude] => SimpleXMLElement Object ( ) [longitude] => SimpleXMLElement Object ( ) [flags] => SimpleXMLElement Object ( ) [images] => SimpleXMLElement Object ( [image] => Array ( [0] => image [1] => image [2] => image [3] => image [4] => image ) ))
Does anyone know how I would be able to search this query for example
$post_code = 43; $min_price = 300; $max_price = 500
and so on.

Looking at the code, the logic seems good to me.
There is something though that might cause the issue.
On line 4 of your code, you have:
$this->properties[] = $property;
It means that you have an array of properties.
But then, you are trying to access the object directly:
if($this->properties->regionID == $post_code) {
$this->properties[] = $property;
}
This looks strange to me. You are trying to see if an abject has the property you want, and then save the same object as it is an array.
So I guess, once you have built your $this->properties array, you just have to loop through it and apply your filters to return an array of properties with just what you are looking for:
foreach($this->properties as $singleProperty)
{
if($singleProperty->regionID == $post_code)
{
$this->foundProperties[] = $singleProperty;
}
}

Related

PHP Object array access with variable

I have a sample object array as a variable $xmlobj
SimpleXMLElement Object(
[SearchId] => 10769920113727_1556288871357_170040
[Categories] => SimpleXMLElement Object
(
[#attributes] => Array
(
[total_subcategories] => 1
)
[SubCategory] => SimpleXMLElement Object
(
[Title] => Reproductor MP3 y Multimedia
[Value] => 122701
[NumberOfProducts] => 1
)
)
[Products] => SimpleXMLElement Object
(
[#attributes] => Array
(
[totalResultsAvailable] => 1
[firstResultPosition] => 1
[totalResultsReturned] => 1
[currency] => EUR
[totalMerchantsAvailable] => 1
[searchOperator] => and
)
[Product] => SimpleXMLElement Object
(
[Offer] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => f94af9ec5186b53051c9ccf083ebddec
[type] => MANUFACTURER_PRODUCTS
)
[Title] => Apple iPod Nano 6 8 GB Gris
[Description] => iPod Nano 6 8 GB - Gris
[LastModified] => 2019-04-26 01:10:56
[MobileFriendly] => false
[Merchant] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 15348713
)
[Name] => Backmarket
)
[Price] => SimpleXMLElement Object
(
[#attributes] => Array
(
[currency] => EUR
)
[Price] => 99.99
[DeliveryCost] => 19.9
[DeliveryCostDetails] => SimpleXMLElement Object
(
[DeliveryCost] => 19.9
)
[TotalPrice] => 119.89
[PriceWithoutRebate] => 190
[Rebate] => 47
)
[ProductClass] => 2
[Availability] => 1
[DeliveryTime] => 24H / 4 días laborables
[Promo] => SimpleXMLElement Object
(
)
[OffensiveContent] => false
[FinancingOption] => SimpleXMLElement Object
(
)
[MerchantCategory] => Alta Tecnología Imágenes y sonidos Reproductor de MP3 Y MP4
[Brand] => Apple
[BrandId] => 211
[GreenProduct] => false
)
)
)
Now when I want to access e.g. price i do it like this:
$product_total_price = $xmlobj->Products->Product->Offer->Price->TotalPrice;
And it's OK - I get what I want, but I am having issue when I want "dynamically" to change what I am looking for like:
$search_part = "Products->Product->Offer->Price->TotalPrice";
$product_total_price = $xmlobj->$search_part;
I obviously get nothing... even when I try:
$product_total_price = $xmlobj."->".$search_part;
So my question is... how to do it ? :)
Thanks !
You will have to construct the path by exploding into an array, then looping to get each property.
For example...
$searchPart = "Products->Product->Offer->Price->TotalPrice";
$searchPath = explode('->', $searchPart);
$current = $xmlobj;
foreach ($searchPath as $segment) {
$current = $current->$segment;
}
var_dump($current);
or you can convert it to an array and then you will be able to get your attributes
$xml = simplexml_load_string($xmlobj);
$json = json_encode($xml);
$arr = json_decode($json,TRUE);
$parseString = 'Products->Product->Offer->Price->#attributes->currency';
$parsePath = explode('->', $parseString);
$current = $arr;
foreach ($parsePath as $segment) {
$current = $current[$segment];
}
var_dump($current);
You can take a look at eval that take your code as a string and evaluates it, but I strongly discourage its usage because it's a potentially (and very big) security hole.
Instead you could use explode passing as first argument -> and then loop over the resulting array to get the value you need:
$search_part = "Products->Product->Offer->Price->TotalPrice";
$chunks = explode("->", $search_part);
foreach ($chunks as $chunk) {
$temp = $xmlobj[$chunk];
}
$product_total_price = $temp;
or something similar, and then you will get you price dynamically
Note that if $xmlObj is of type Object you will need to use $xmlObj->{$chunk} instead of $xmlobj[$chunk]

How to get Maximum value from array inside array in php

I have my array like this, I want to fetch Score and Label from the array categories. I want to get my result like this as in here in category pornography its score is 0.25 and Non-Standard Content has score 0.1
so the result should be label=>'pornography' and score 0.25.
I tried getting values of label and score in an array like
$categories= array('pornography'=>0.25,'Non-Standard Content'=>0.1)
$value = max($categories);
then $value= 0.25
I want label also.
[text] =>
[taxonomy] => iab-qag
[language] => en
[categories] => Array
(
[0] => stdClass Object
(
[confident] =>
[score] => 0.25
[label] => Pornography
[links] => Array
(
[0] => stdClass Object
(
[rel] => self
)
[1] => stdClass Object
(
[rel] => parent
)
)
[id] => IAB25-3
)
[1] => stdClass Object
(
[confident] => 1
[score] => 0.1
[label] => Non-Standard Content
[links] => Array
(
[0] => stdClass Object
(
[rel] => self
)
)
[id] => IAB25
)
)
)
Somebody posted here Answer but I don't know why it is not appearing now. I used that solution to solve my problem here is the solution:
$maxScore = 0; $maxCat = [];
foreach($data[$x]->categories as $c) {
$cat[] = ['label' => $c->label, 'score' => $c->score];
if ($maxScore < $c->score) {
$maxScore = $c->score;
$maxCat = [
'label' => $c->label, 'score' => $c->score
];
}
Hope it will help somebody. Thanks to anonymous whoever posted this solution.

Returning an array within multiple objects and arrays

I can't seem to figure out the correct syntax to print:
[Agriculture] => AGR
[Animals] => AN
[Arts and Humanities] => ART
within the $TOPIC object.
What makes this a bit more confusing is that $TOPIC is in an object that can be called in a different order than this example. So instead of [3] => stdClass Object, it could be [4] => stdClass Object, (or any number).
Some sample foreach syntax is included below; it doesn't work though.
stdClass Object
(
[123456] => stdClass Object
(
[required_actions] => Array
(
[1] => stdClass Object
(
[maxlength] =>
[value] => $MESSAGE
[options_hash] =>
)
[2] => stdClass Object
(
[maxlength] =>
[value] => $NAME_PREFIX
[options_hash] => stdClass Object
(
[Ms.] => Ms.
[Mrs.] => Mrs.
[Mr.] => Mr.
)
)
[3] => stdClass Object
(
[maxlength] =>
[value] => $TOPIC
[options_hash] => stdClass Object
(
[Agriculture] => AGR
[Animals] => AN
[Arts and Humanities] => ART
)
)
)
)
)
foreach ($json->123456->required_actions as $info) {
echo $info->value => $TOPIC->options_hash;
}
The solution is to search for the parent object by value, and then request the child object's array. Here is what I used:
foreach ($json->123456->required_actions as $info) {
if ('$TOPIC' == $info->value) {
print_r($info->options_hash);
}
}

Foreach loop with mixed stdClass objects and arrays

Here I have an output from a website using Soap
stdClass Object
(
[page] => 0
[items] => 3
[total] => 3
[saleItems] => stdClass Object
(
[saleItem] => Array
(
[0] => stdClass Object
(
[reviewState] => open
[trackingDate] => 2011-11-03T01:06:43.547+01:00
[modifiedDate] => 2011-11-03T01:06:43.677+01:00
[clickDate] => 2011-10-30T22:57:57.383+01:00
[adspace] => stdClass Object
(
[_] => Beslist.nl [id] => 1437603
)
[admedium] => stdClass Object
(
[_] => 001. Program logo
[id] => 535098
)
[program] => stdClass Object
(
[_] => Zavvi NL
[id] => 8991
)
[clickId] => 1565847253976339456
[clickInId] => 0
[amount] => 40.45
[commission] => 2.83
[currency] => EUR
[gpps] => stdClass Object
(
[gpp] => Array
(
[0] => stdClass Object
(
[_] => shoplink
[id] => zpar0
)
)
)
[trackingCategory] => stdClass Object
(
[_] => Default
[id] => 45181
)
[id] => 46a4f84a-ba9a-45b3-af86-da5f3ec29648
)
)
)
)
I want to have the data (with a foreach loop) from program, commission and gpp->_. I can get the data from program and commission like this:
foreach ($sales->saleItems->saleItem as $sale) {
$programma = $sale->program->_;
$commissie = $sale->commission;
}
Works like a charm. However I can't get the data from the gpp->_ (want to have shoplink as result). I currently have:
foreach ($sales->saleItems->saleItem->gpps->gpp as $tracking) {
echo $tracking->_;
}
I get the error "Trying to get property of non-object". I've tried lots if variations and can't get it to work. Think I'm really close. Anyone has a solution?
This should work
foreach ($sales->saleItems->saleItem as $sale) {
foreach($sale->gpps->gpp as $tracking) {
echo $tracking->_;
}
As saleItem is an array, you won't be able to use chaining on it.

Use a foreach loop to access the array within this queryresult object?

A print_r of my object ($results) returns the following:
QueryResult Object
( [queryLocator] => [done] => 1 [records] =>
Array ( [0] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0167 [Partner_Research_Name__c] => MM Sample Organization-TBR Partner 2011 [Id] => a0V80000003FwjjEAC ) [Id] => a0V80000003FwjjEAC )
[1] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0170 [Partner_Research_Name__c] => Kansas City, Missouri Public Schools-TBR Partner 2011 [Id] => a0V80000003Fxf9EAC ) [Id] => a0V80000003Fxf9EAC )
[2] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0169 [Partner_Research_Name__c] => Newark Public Schools-TBR Partner 2011 [Id] => a0V80000003FxQ2EAK ) [Id] => a0V80000003FxQ2EAK )
[3] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0168 [Partner_Research_Name__c] => Breakthrough Charter Schools-TBR Partner 2011 [Id] => a0V80000003FxPxEAK ) [Id] => a0V80000003FxPxEAK )
[4] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0004 [Partner_Research_Name__c] => KIPP, San Antonio-TBR Partner 2011 [Id] => a0V80000003FrBUEA0 ) [Id] => a0V80000003FrBUEA0 )
[5] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0003 [Partner_Research_Name__c] => KIPP, Chicago - Gary-TBR Partner 2011 [Id] => a0V80000003FrB5EAK ) [Id] => a0V80000003FrB5EAK )
[6] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0023 [Partner_Research_Name__c] => Harlem Village Academies-TBR Partner 2011 [Id] => a0V80000003FrEOEA0 ) [Id] => a0V80000003FrEOEA0 ) ) [size] => 7 )
I want to use a loop similar to the what is shown below to display a series of results however the foreach statement is incorrect.
foreach ($results as $result)
{
$id = $result[fields][Id];
$name = $result[fields][Partner_Research_Name__c];
$url = $result[fields][Partner_Research_URL__c];
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
What changes do I need to make to the foreach statement to get my code back on track?
What helps me in problems like this is to try to print inside the foreach loop. For example, you can do a var_dump of each $result and see what that structure is, and it could help determine how to proceed.
Here is how I eventually did it, thanks for the help provided by contributors.
foreach ($results->records as $result)
{
$id = $result->fields->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
$results is the name of the QueryResults object, I don't know what the real name in your code is.
foreach ($results->records as $result)
{
$id = $result->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
If I'm reading your sample correctly, your items are std objects instead of arrays. You may need to reference them like this:
foreach ($results as $result)
{
$id = $result->fields->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
Your print_r sample above is difficult to read. If you could provide it with the indentation it would be helpful.

Categories