在 PHP 中按特定顺序对数组重新排序

时间:2021-04-11 14:17:36

标签: php arrays

所以我正在尝试重新排序我的 Array of arrays,但我很难这样做,我希望能够使用 usort 但没有运气。

到目前为止,这是我的尝试 - 我构建了一个函数,我将按特定顺序定义和排序项目,如下所示,它不起作用

function build_sorter($key): Closure
{
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}
uasort($all_fields, build_sorter('job_title'));
uasort($all_fields, build_sorter('job_category'));

这是我的数组数组 - 我如何自定义定义我的排序顺序并首先拥有职位,然后是 job_category 等等? (我有 10 多个字段,所以我想为每个数组指定一个特殊的顺序):

$all_fields 输出以下内容:

array (size=12)
  'job_title' => 
    array (size=5)
      'label' => string 'Listing Name' (length=12)
      'type' => string 'text' (length=4)
      'required' => boolean true
      'placeholder' => string 'Your listing name' (length=17)
      'priority' => int 1
  'job_description' => 
    array (size=5)
      'label' => string 'Description' (length=11)
      'type' => string 'wp-editor' (length=9)
      'required' => boolean true
      'priority' => float 2.2
      'placeholder' => string 'An overview of your listing and the things you love about it.' (length=61)
  'job_category' => 
    array (size=8)
      'label' => string 'Listing category' (length=16)
      'type' => string 'term-multiselect' (length=16)
      'required' => boolean true
      'placeholder' => string 'Choose one or more categories' (length=29)
      'priority' => float 2.3
      'default' => string '' (length=0)
      'taxonomy' => string 'job_listing_category' (length=20)
      'description' => string '<span class="description_tooltip right">Visitors can filter their search by the categories and amenities they want - so make sure you choose them wisely and include all the relevant ones</span>' (length=193)

0 个答案:

没有答案