我正在使用Wordpress store locator plugin。
我有一个带存储的数组,我想按字母顺序对结果进行排序,但有两个“特殊存储”应该是我输出数组时的第一个结果。
我已经在基本的例子中得到了我想要的东西
$stores = array("A", "B", "C", "D");
usort($stores, function($a, $b) {
if ($b == "C") {
return 1;
}
});
foreach ($stores as $store) {
echo $store;
}
但我不知道如何使用插件实现这一目标。根据docs of the plugin,这是你如何排序商店。
add_filter( 'wpsl_store_data', 'custom_result_sort' );
function custom_result_sort( $store_meta ) {
$custom_sort = array();
foreach ( $store_meta as $key => $row ) {
$custom_sort[$key] = $row['store'];
}
array_multisort( $custom_sort, SORT_ASC, SORT_REGULAR, $store_meta );
return $store_meta;
}
它使用array_multisort
,我不知道我是否可以使用usort以某种方式使两个特殊商店首先出现。任何想法如何做到这一点?
您可以尝试使用此解决方案。只需在商店名称前添加前缀,然后使用array_multisort()
和SORT_ASC
进行排序:
SORT_STRING
function custom_result_sort( $store_meta ) {
$custom_sort = array();
foreach ( $store_meta as $key => $row ) {
$store = $row['store'];
if (($store == 'SpecialStore1') || ($store == 'SpecialStore2')) {
$prefix = '0_';
} else {
$prefix = '1_';
}
$custom_sort[$key] = $prefix.$store;
}
array_multisort( $custom_sort, SORT_ASC, SORT_STRING, $store_meta );
return $store_meta;
}