PHP按字母顺序排序数组,但应首先显示特定项

问题描述 投票:0回答:2

我正在使用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以某种方式使两个特殊商店首先出现。任何想法如何做到这一点?

php arrays sorting
2个回答
1
投票

您可以尝试使用此解决方案。只需在商店名称前添加前缀,然后使用array_multisort()SORT_ASC进行排序:

SORT_STRING

0
投票
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.