Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP按字母顺序对数组排序,但应首先显示特定项_Php_Arrays_Sorting - Fatal编程技术网

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

PHP按字母顺序对数组排序,但应首先显示特定项,php,arrays,sorting,Php,Arrays,Sorting,我在用电话 我有一个带有存储的数组,我想按字母顺序对结果进行排序,但是有两个特殊的存储,它们应该是我输出数组时的第一个结果 我已经在一个基本的例子中得到了我想要的 $stores = array("A", "B", "C", "D"); usort($stores, function($a, $b) { if ($b == "C") { return 1; } }); foreach ($stores as $store) { echo $store; } 但我不知道如何用这个

我在用电话

我有一个带有存储的数组,我想按字母顺序对结果进行排序,但是有两个特殊的存储,它们应该是我输出数组时的第一个结果

我已经在一个基本的例子中得到了我想要的

$stores = array("A", "B", "C", "D");

usort($stores, function($a, $b) {

if ($b == "C") {
  return 1;
}

});

foreach ($stores as $store) {
  echo $store;
}
但我不知道如何用这个插件实现这一点。根据这张表,你可以对商店进行分类

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让这两个特殊的存储首先出现。有什么办法吗?

你可以试试这个解决方案。只需在存储名称之前添加前缀,然后使用带有sort\u ASC和sort\u字符串的数组\u multisort进行排序:

$stores = array("A", "B", "C", "D");
asort($stores);
foreach ($stores as $key => $val) {
    echo "$key = $val\n";
}

这个插件只是提供了一个过滤器来对结果进行排序,但这并不意味着你必须这样做。您的自定义_result_sort函数可以对数据进行任意排序,它只需在最后返回已排序的数组。首先,您只需找出要排序的值在数据结构中的位置。请发布需要排序的数据。如上所述,不需要按原样使用代码,只需输出格式正确即可。
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;
}