我正在使用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;
}
但是我不知道如何使用插件来实现。根据{{3}},这是您对商店进行排序的方式。
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使这两个特殊商店首先出现。任何想法如何做到这一点?
答案 0 :(得分:1)
您可以尝试使用此解决方案。只需在商店名称前添加前缀,然后使用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;
}
答案 1 :(得分:0)
$stores = array("A", "B", "C", "D");
asort($stores);
foreach ($stores as $key => $val) {
echo "$key = $val\n";
}