对多维数组进行升序排序,并指定一个子数组始终为第一个

时间:2017-09-04 17:15:30

标签: php sorting multidimensional-array sticky

我有一个多维数组:

$array = array (
  "B" => array ("Banana", "Yello"),
  "O" => array ("Orange", "Orange"),
  "A" => array ("Apple", "Green"),
  "S" => array ("Strawberry", "Red")
);

$o = $array['O']; // this is the letter O not zero
asort($array);
array_unshift($array, $o);

现在我想使用asort()重新排序数组,但保留“O”作为第一个条目:

O, A, B, S

这里的问题是我得到了

O, A, B, O, S

如何摆脱第二个“O”?

注意:我已经问了一个类似的问题,但是使用了不同的数组here

3 个答案:

答案 0 :(得分:2)

您只需要unset($array['O']);

<?php
    $array = array (
  "B" => array ("Banana", "Yello"),
  "O" => array ("Orange", "Orange"),
  "A" => array ("Apple", "Green"),
  "S" => array ("Strawberry", "Red")
);

$o = $array['O']; // this is the letter O not zero
asort($array);
unset($array['O']);
array_unshift($array, $o);
print_r($array);
?>

现场演示:https://eval.in/855161

答案 1 :(得分:2)

尝试此操作以保留数组键:

$array = array (
  "B" => array ("Banana", "Yello"),
  "O" => array ("Orange", "Orange"),
  "A" => array ("Apple", "Green"),
  "S" => array ("Strawberry", "Red")
);

$key = 'O';

asort($array);
$array = (array_key_exists($key, $array)) ? array($key => $array[$key]) + $array : $array;

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

http://www.phpwin.org/s/ltHbIV

http://php.net/manual/en/language.operators.array.php

归功于@salathe

答案 2 :(得分:2)

比调用多个函数更好的方法是使用一个用于执行自定义键排序的函数。对于较新的php开发人员来说,这可能是一个困难的阅读,但它是适合这项工作的正确工具......

*请注意,当粘滞键丢失时,此自定义排序不会失败,因此无需事先检查数组中是否存在该键。

方法: uksort()PHP<7 no-strcmp() Demo)(PHP<7 strcmp() Demo)(PHP7+ <=> Demo

$array=["B"=>["Banana","Yello"],"O"=>["Orange","Orange"],"A"=>["Apple", "Green"],"S"=>["Strawberry","Red"]];

$sticky='O';

uksort($array,function($a,$b)use($sticky){
    if($a===$sticky) return -1;  // prioritize if $a is sticky, regardless of $b
    if($b===$sticky) return 1;  // deprioritize if $b is sticky match
    /* PHP7+ technique:
        return $a<=>$b;
    */
    // or one of two PHP<7 techniques:
    /*
       if($a===$b) return 0;
       return $a>$b?1:-1;
    */
    return strcmp($a,$b);
});

var_export($array);

输出:

array (
  'O' => 
  array (
    0 => 'Orange',
    1 => 'Orange',
  ),
  'A' => 
  array (
    0 => 'Apple',
    1 => 'Green',
  ),
  'B' => 
  array (
    0 => 'Banana',
    1 => 'Yello',
  ),
  'S' => 
  array (
    0 => 'Strawberry',
    1 => 'Red',
  ),
)