array_groupBy - additional fields.
2 posts by 2 authors in: Forums > CMS Builder
Last Post: January 14, 2016 (RSS)
By Toledoh - January 10, 2016
Hi Guys,
I've got a page which is showing a "collection" which is a grouping of products. Each product is also within a "series" or a sub-group.
// load record from 'collections'
list($collectionsRecords, $collectionsMetaData) = getRecords(array(
'tableName' => 'collections',
'where' => whereRecordNumberInUrl(0),
'limit' => '1',
));
$collectionsRecord = @$collectionsRecords[0]; // get first record
if (!$collectionsRecord) { dieWith404("Record not found!"); } // show error message if no record found// load records from 'products'
list($productsRecords, $productsMetaData) = getRecords(array(
'tableName' => 'products',
'where' => 'collection='.$collectionsRecord['num'].''
));$productsSortedBySeries = array_groupBy($productsRecords, 'series:label', true);
I can then display each "series", and list the "products" in each by.
<?php foreach($productsSortedBySeries as $series => $products): ?>
<div class="col-xs-4">
<h2><?php echo htmlencode($series) ?></h2>
<div class="row">
<?php foreach ($products as $record): ?>
<div class="col-xs-4">
<div class="thumbnail">
<?php echo $record['colour'] ?>
</div>
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
<?php echo htmlencode($series) ?> displays the series:label. Is there any way I can get additional fields such as series['content'] etc?
Tim (toledoh.com.au)
Hi Tim,
I thought I'd add the solution we found to this problem in here.
The problem was that we want to get the appropriate series data before we loop through the products. So the easiest solution is to get each series records directly from the database as we need them:
<div class="row">
<?php foreach($productsSortedBySeries as $seriesNum => $products): ?>
<div class="col-xs-4">
<?php $series = mysql_get('series', $seriesNum); ?>
<h2><?php echo @$series['title']; ?></h2>
<p><?php echo @$series['content']; ?></p>
<div class="row">
<?php foreach ($products as $record): ?>
<div class="col-xs-4">
<div class="thumbnail">
<?php echo $record['colour'] ?>
</div>
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
</div>
So the above code uses the current series number to retrieve the related series record, and display its title and content before we cycle through the product records.
Thanks,
Greg
PHP Programmer - interactivetools.com