Jump to content

Sorting pages with numerical names last


a-ok
 Share

Recommended Posts

@oma

I assume you want them ordered ascending and the ones starting with a number at the end.

You could do this by storing the numerical names in a variable and echoing that variable after the "normal" names.

$numericalNames = "";
$normalNames = "";
$names = $pages->find("template=template_name");
foreach($names as $n)
{
	/* get the first letter of the current name */
	$firstLetter = substr($n->name, 0, 1);
	$regexPattern = "/[0-9]/";
	// if first letter is a number
	if(preg_match($regexPattern, $firstLetter))
	{
		$numericalNames .= $n->name;
	}
	else
	{
		$normalNames .= $n->name;
	}
}
echo $normalNames;
echo $numericalNames;

 

  • Like 2
Link to comment
Share on other sites

If you only want to sort in-memory, getting the pages as a plain array and using a custom sort function should do the trick:

<?php

$ps = $pages->find('yourselector')->getArray();

usort($ps, function($a, $b) {
	$na = $a->name;
	$nb = $b->name;
	if(!ctype_digit($na) && !ctype_digit($nb)) return strcmp($na, $nb);
	if(ctype_digit($na) && ctype_digit($nb)) return strcmp($na, $nb);
	
	return (ctype_digit($na)) ? 1 : -1;
});

foreach($ps as $p) echo $p->name . PHP_EOL;

 

  • Like 6
Link to comment
Share on other sites

Thanks, folks! Has anyone else had this 'issue', or is it generally common practice to have numbers first, rather than last? I wonder if it would be possible to suggest an PW API avaliable for an option like this?

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...