Sort foreach loop to display records with uploads first

4 posts by 4 authors in: Forums > CMS Builder
Last Post: November 30, 2017   (RSS)

Hi, Zicky.

There may be a more elegant method, but this is what I would do.

// load records WITH a photo
list($menuRecordsPHOTO, $menuMetaData) = getRecords(array(
'tableName' => 'menu',
'loadUploads' => true,
'allowSearch' => false,
));
// load records WITHOUT a photo
list($menuRecordsNOPHOTO, $menuMetaData) = getRecords(array(
'tableName' => 'menu',
'loadUploads' => true,
'allowSearch' => false,
));

<?php foreach ($menuRecordsPHOTO as $record): ?>
<?php if ($record['photo']): ?>
<h1><a href="<?php echo $record['_link'] ?>"><?php echo htmlencode($record['name']) ?></a></h1>
<?php echo $record['content']; ?><br/>
Price: $<?php echo htmlencode($record['price']) ?><br/>
<?php foreach ($record['photo'] as $index => $upload): ?>
<a href="<?php echo $record['_link'] ?>">
<img src="<?php echo htmlencode($upload['thumbUrlPath3']) ?>" alt="<?php echo htmlencode($upload['info1']) ?>" /></a>
<?php endforeach ?>
<hr>
<?php endif; ?>
<?php endforeach ?>

<?php foreach ($menuRecordsNOPHOTO as $record): ?>
<?php if (!$record['photo']): ?>
<h1><a href="<?php echo $record['_link'] ?>"><?php echo htmlencode($record['name']) ?></a></h1>
<?php echo $record['content']; ?><br/>
Price: $<?php echo htmlencode($record['price']) ?><br/>
<hr>
<?php endif; ?>
<?php endforeach ?>

Hope that helps. :)

~ Deborah

By Toledoh - November 30, 2017 - edited: November 30, 2017

Could you just do 2 loops?

<?php foreach ($menuRecords as $record): ?>
<?php if ($record['photo']): ?>

Show records with images in the order set via CMSB

<?php endif; ?>
<?php endforeach ?>

<?php foreach ($menuRecords as $record): ?>
<?php if (!$record['photo']): ?>

Show records with NO images in the order set via CMSB

<?php endif; ?>
<?php endforeach ?>

Cheers,

Tim (toledoh.com.au)

By leo - November 30, 2017

Hi Zicky,

An easy solution will be using usort() to specify how you want the array to be sorted. You can check the manual here for more information: http://php.net/manual/en/function.usort.php

But basically the code might be something like this:

// sort array
usort($menuRecords, 'sortByUploads');

// sort function
function sortByUploads($prev, $next){
  if(!empty($prev['photo']) && empty($next['photo'])){
    // $prev has higher priority then $next
    return -1;
  }
  else if(empty($prev['photo']) && !empty($next['photo'])){
    // $next has higher priority then $prev
    return 1;
  }
  else{
    // $prev and $next have the same priority
    return 0;
  }
}

Hope this helps and let me know if you have any questions!

Leo - PHP Programmer (in training)
interactivetools.com