【发布时间】:2020-02-07 10:51:43
【问题描述】:
我正在使用 WordPress 提供的get_posts 来提供一组帖子对象。该数组的简化版本如下;
$zones = array
0 =>
object
public 'post_title' => string 'Zone Five: Banana'
1 =>
object
public 'post_title' => string 'Zone Eight: Banana'
2 =>
object
public 'post_title' => string 'Zone Six: Banana'
3 =>
object
public 'post_title' => string 'Zone Seven: Banana'
4 =>
object
public 'post_title' => string 'Zone Four: Cherry'
5 =>
object
public 'post_title' => string 'Zone Two: Orange'
6 =>
object
public 'post_title' => string 'Zone Three: Avocado'
7 =>
object
public 'post_title' => string 'Zone One: Apple'
如您所见,帖子标题不按顺序排列。显然,按字母排序是行不通的。
理想情况下,数组的第一项是Zone One: Apple,最后一项是Zone Eight: Banana
我认为usort 是要使用的 PHP 函数,但我不知道如何比较子字符串和整个字符串。
这是一些适用于全文匹配的代码; (借自另一个有用的堆栈溢出帖子)
$order = array_flip(['Zone One: Apple', 'Zone Two: Orange', 'Zone Three: Avocado', 'Zone Four: Cherry', 'Zone Five: Banana', 'Zone Six: Banana', 'Zone Seven: Banana', 'Zone Eight: Banana']); // restructure with values as keys, and keys as order (ASC)
$outlier = 1 + max($order);
usort($zones, function ($a, $b) use (&$order, $outlier) { // make $order modifiable with &
if (!isset($order[$a->post_title])) {$order[$a->post_title] = $outlier;} // update lookup array with [id]=>[outlier number]
if (!isset($order[$b->post_title])) {$order[$b->post_title] = $outlier;} // and again
return $order[$a->post_title] <=> $order[$b->post_title];
});
理想情况下,我想按子字符串排序;
$order = ['一', '二', '三', '四', '五', '六', '七', '八'];
【问题讨论】:
-
您的所有帖子标题是否总是以“区域”开头,然后是一、二等等?