我如何排序这个数组的值“order”键?

尽管这些值目前是连续的,但它们并不总是连续的。

Array
(
    [0] => Array
        (
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [order] => 3
        )

    [1] => Array
        (
            [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
            [title] => Free
            [order] => 2
        )

    [2] => Array
        (
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1
        )
)

当前回答

 example  with class:
 
 class user
 {
     private $key;

     public function __construct(string $key)
     {
         $this->key = $key;
     }

     public function __invoke($a, $b)
     {
         return $a[$this->key] <=> $b[$this->key];
     }
 }

 $user = [
     ['id' => 1, 'name' => 'Oliver', 'id_card' => 4444],
     ['id' => 3, 'name' => 'Jack', 'id_card' => 5555],
     ['id' => 2, 'name' => 'Harry', 'id_card' => 6666]
 ];

 // sort user by id
 usort($user, new user('id'));
 var_dump($user);

其他回答

$sort = array();
$array_lowercase = array_map('strtolower', $array_to_be_sorted);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);

这可以同时考虑大写字母和小写字母。

让我们面对这个问题:PHP没有一个简单的开箱即用的函数来正确处理每个数组排序场景。

这个例程很直观,这意味着更快的调试和维护:

// Automatic population of the array
$tempArray = array();
$annotations = array();
// ... some code
// SQL $sql retrieves result array $result
// $row[0] is the ID, but is populated out of order (comes from
// multiple selects populating various dimensions for the same DATE
// for example
while($row = mysql_fetch_array($result)) {
    $needle = $row[0];
    arrayIndexes($needle);  // Create a parallel array with IDs only
    $annotations[$needle]['someDimension'] = $row[1]; // Whatever
}
asort($tempArray);
foreach ($tempArray as $arrayKey) {
    $dataInOrder = $annotations[$arrayKey]['someDimension'];
    // .... more code
}

function arrayIndexes ($needle) {
    global $tempArray;
    if (!in_array($needle, $tempArray)) {
        array_push($tempArray, $needle);
    }
}

PHP 7.4及以上版本的“箭头函数”语法:

uasort($yourArray, fn($a, $b) => $a['order'] <=> $b['order']);

漂亮的打印

echo '<pre>';
print_r($yourArray);

使用array_multisort(), array_map()

array_multisort(array_map(function($element) {
      return $element['order'];
  }, $array), SORT_ASC, $array);

print_r($array);

DEMO

 example  with class:
 
 class user
 {
     private $key;

     public function __construct(string $key)
     {
         $this->key = $key;
     }

     public function __invoke($a, $b)
     {
         return $a[$this->key] <=> $b[$this->key];
     }
 }

 $user = [
     ['id' => 1, 'name' => 'Oliver', 'id_card' => 4444],
     ['id' => 3, 'name' => 'Jack', 'id_card' => 5555],
     ['id' => 2, 'name' => 'Harry', 'id_card' => 6666]
 ];

 // sort user by id
 usort($user, new user('id'));
 var_dump($user);