chadmin
Post count: 1
|
I have created an object with a list of stores and associated field data. I’m trying to iterate through this list and break out the city of the stores like so:
City 1
store 1
store 2
store 3
City 2
store 1
store 2
store 3
However, my results ALWAYS come out like this:
City 1
store 1
City 1
store 2
City 1
store 3
City 2
store 1
City 2
store 2
City 2
store 3
Because the object: $mystore->set(“address”)->field(“city”) as $city=>$value is always unique, I can’t seem to use any compare or even unique_array.
How can I achieve this?
|
chadmin
Post count: 1
|
I found a solution, but is there a better way to do this?
I used the value() method to set my variable which then I could do a compare like so:
<?php
$oldCity=null;$newCity=null;
foreach ($myquery as $mystore) :
$newCity = $mystore->address->city->value();
if($oldCity!==$newCity):
echo “<h5>”.$newCity.”</h5><br />”;
endif;
$oldCity=null;
$oldCity=$newCity;
$newCity=null;
endforeach;
?>
Results gave me a list of non-repeating cities.
|
traversal
Post count: 207
|
Hey there. Certainly using the value method is the right way to go, as using the “field” method returns you an object, which will indeed always be unique.
There is one alternative way to do this however.
Assuming your store was a post type, and that your field set was called “address”, try something like this:
https://gist.github.com/traversal/2c30d1bc5e74577c4c83
The $wf->stores call will give you a collection of store posts, which I’ve ordered by title ascending. You can then call WOOF_Collection::group_by passing in “address.city” to indicate the field “city” in field set “address”, to group by that field.
group_by returns an associative array with:
* keys of unique string values corresponding to the unique cities.
* values being collections of posts with that city value.
So you’re outer loop then displays the cities, and has an inner loop which loops over the stores for that city.
This is more concise, but certainly less obvious than your approach (which is perfectly valid too!).
|