Jump to content

How to 'group by' a field in processwire?


SIERRA
 Share

Recommended Posts

Hai ,


Coding:
  <select name="eventstart" id="eventstart">

        <option value=""><?php echo $lang['select_event_start']; ?></option>

        <?php
        
        foreach( $events_pages->events->find($filter.",  sort=event_start") as $event) {?>

           <option value="<?php echo $event->event_start;?>"><?php echo $event->event_start;?></option>        

        <?php } ?>        

        </select>

It results:

image.png.0bc9c9c815e9a415800a5180705c6d48.png

But , i need result without repeated dates.how to 'groupby' event_start field in processwire ?could you please sugguest me
Thank you

Link to comment
Share on other sites

You could probably use unique(): http://cheatsheet.processwire.com/pagearray-wirearray/getting-items/a-unique/

Either way, I would avoid doing a find() in every foreach - that's inefficient. Define a variable for the results before your foreach.

$results = $events_pages->events->find($filter.",  sort=event_start");
$unique = $results->unique();
foreach($unique as $e) // etc.

 

Link to comment
Share on other sites

There's no group by feature in PW. WireArray->unique() doesn't work for this purpose.

Using the API you could Just build an array using WireArray->explode() and use array_unique(). Depending how large the result set is you could cache the array so it only builds the array when it expires or based on a selector.

$uniquedates = $cache->get("uniquedates", "template=basic-page", function(){
	return array_unique(wire("pages")->find("template=basic-page, sort=date")->explode("date"));
});

print_r($uniquedates);

 If the amount of entries is very large and it would take several seconds to build the array, it could make sense to use something like direct SQL query.

  • Like 2
Link to comment
Share on other sites

11 minutes ago, Soma said:

If the amount of entries is very large and it would take several seconds to build the array, it could make sense to use something like direct SQL query.

It's easy using RockFinder. See the example in the docs: https://gitlab.com/baumrock/RockFinder#custom-sql-aggregations-groupings-distincts

  • Like 3
Link to comment
Share on other sites

  • 3 months later...
  • 1 year later...

Maybe below code can help for simple group by date for example  :

$list = $pages->find("template=event");  
$groups = array();  
foreach ($list as $item) {  
	$groups["$item->date"][] = $item->id; 
}

foreach($groups as $key => $gr){         
	echo $key."<br>";
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...