php-按自定义条件对数组进行排序 [英] php - sort array by custom criteria

查看:63
本文介绍了php-按自定义条件对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组:

object1->
name="Name1"
key="key1"

object2->
name="Name2"
key="key2"

object3->
name="Name3"
key="key3"

和一组优先级键:

$keys = ["key3", "key1"];

我需要根据优先级键对对象数组进行排序,因此结果应为:

I need to sort the array of objects based on priority keys, so the result should be:

object3:
name="Name3"
key="key3"

object1->
name="Name1"
key="key1"

object2:
name="Name2"
key="key2"

最好的方法是什么?

推荐答案

该想法是将优先级添加为整数,并使用 usort()

The idea is to add a priority as integer, and sort the array from the highest integer to the lowest using usort()

例如您有此数据

 <?php

 $data = [];

 $data[0] = new stdClass;
 $data[0]->name = "name1";
 $data[0]->key = 'key1';

 $data[1] = new stdClass;
 $data[1]->name = "name2";
 $data[1]->key = 'key2';

 $data[2] = new stdClass;
 $data[2]->name = "name3";
 $data[2]->key = 'key3';


 $keys = ["key3", "key1"];

您可以通过这种方式对其进行排序

you can sort it this way

function sortByPriority($data , $keys){
    $priority = array();
    $i = count($keys);
    foreach ($keys as $key => $value) {
      $i--;
      $priority[$value] = $i;
    }
    usort($data, function($a, $b) use($priority){
      $a = isset($priority[$a->key]) ? $priority[$a->key] : -1;
      $b = isset($priority[$b->key]) ? $priority[$b->key] : -1;
      return $b - $a;
    });

    return $data;
 }


 var_dump(sortByPriority($data, $keys));    

样本输出

array (size=3)
  0 => 
    object(stdClass)[3]
      public 'name' => string 'name3' (length=5)
      public 'key' => string 'key3' (length=4)
  1 => 
    object(stdClass)[1]
      public 'name' => string 'name1' (length=5)
      public 'key' => string 'key1' (length=4)
  2 => 
    object(stdClass)[2]
      public 'name' => string 'name2' (length=5)
      public 'key' => string 'key2' (length=4)    

这篇关于php-按自定义条件对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆