我有一个看起来像这样的对象数组,请注意,create_time已通过MYSQL对它们进行了排序:
array (size=5)
0 =>
object(stdClass)[38]
public 'vacancy_id' => int 5
public 'title' => string 'test title' (length=10)
public 'create_time' => string '2018-10-05 11:15:34' (length=19)
public 'language_iso' => string 'NL' (length=2)
1 =>
object(stdClass)[42]
public 'vacancy_id' => int 9
public 'title' => string 'test title 5' (length=12)
public 'create_time' => string '2018-08-05 11:15:34' (length=19)
public 'language_iso' => string 'EN' (length=2)
2 =>
object(stdClass)[40]
public 'vacancy_id' => int 7
public 'title' => string 'test title 3' (length=12)
public 'create_time' => string '2018-08-05 11:15:34' (length=19)
public 'language_iso' => string 'FR' (length=2)
3 =>
object(stdClass)[39]
public 'vacancy_id' => int 6
public 'title' => string 'test title 2' (length=12)
public 'create_time' => string '2018-06-05 11:15:34' (length=19)
public 'language_iso' => string 'FR' (length=2)
4 =>
object(stdClass)[41]
public 'vacancy_id' => int 8
public 'title' => string 'test title 4' (length=12)
public 'create_time' => string '2018-02-05 11:15:34' (length=19)
public 'language_iso' => string 'NL' (length=2)
在我的页面上,我正在实现排序功能。 (目前)有4种排序选项:
在上面给出的数组示例中,假设我要按“ FR语言iso”进行排序。这意味着我希望我的结果集如下所示:
array (size=5)
0 =>
object(stdClass)[40]
public 'vacancy_id' => int 7
public 'title' => string 'test title 3' (length=12)
public 'create_time' => string '2018-08-05 11:15:34' (length=19)
public 'language_iso' => string 'FR' (length=2)
1 =>
object(stdClass)[39]
public 'vacancy_id' => int 6
public 'title' => string 'test title 2' (length=12)
public 'create_time' => string '2018-06-05 11:15:34' (length=19)
public 'language_iso' => string 'FR' (length=2)
2 =>
object(stdClass)[38]
public 'vacancy_id' => int 5
public 'title' => string 'test title' (length=10)
public 'create_time' => string '2018-10-05 11:15:34' (length=19)
public 'language_iso' => string 'NL' (length=2)
3 =>
object(stdClass)[42]
public 'vacancy_id' => int 9
public 'title' => string 'test title 5' (length=12)
public 'create_time' => string '2018-08-05 11:15:34' (length=19)
public 'language_iso' => string 'EN' (length=2)
4 =>
object(stdClass)[41]
public 'vacancy_id' => int 8
public 'title' => string 'test title 4' (length=12)
public 'create_time' => string '2018-02-05 11:15:34' (length=19)
public 'language_iso' => string 'NL' (length=2)
因此在此示例中,结果必须包含:
我一直在使用PHP的usort函数中的自定义函数完全空白。
答案 0 :(得分:1)
您可以(也许应该)完全从MySQL处理此排序要求:
SELECT vacancy_id, title, create_time, language_iso
FROM yourTable
ORDER BY
IF(language_iso = 'FR', 0, 1),
create_time;
上面的ORDER BY
子句将首先覆盖法语记录,其次是所有其他语言,而create_time
则是第二步的排序。
虽然可以尝试对PHP中的给定数组/结果集进行排序,但实际上您可能希望始终查询,因为基础数据可能会过时。