質問

Let's say I have an array called $array that looks like this once I run asort on it:

Array
(
    [1] => Apples
    [2] => Bananas
    [3] => Cherries
    [4] => Donuts
    [5] => Eclairs
    [6] => Fried_Chicken
)

What is the simplest way to make it so that, after sorting alphabetically, the key that has the value "Donuts" is removed and then put at the end?

役に立ちましたか?

解決 2

I came up with this. Tested it and confirmed it works. Reordered your array so I could actually see the sorting.

$arr = Array(
  1 => "Fried_Chicken",
  2 => "Donuts",
  3 => "Bananas",
  4 => "Apples",
  5 => "Eclairs",
  6 => "Cherries"
);  

// Get donut and key
$donut_key = array_search("Donuts", $arr);
$donut = $arr[$donut_key];  // If you don't need to keep the value, skip this line

// Remove donut
unset($arr[$donut_key]);

// Sort
asort($arr);

// Append Donut
$arr += array($donut_key => $donut);

Array Search http://php.net/manual/en/function.array-search.php

Key preserving append http://www.vancelucas.com/blog/php-array_merge-preserving-numeric-keys/

他のヒント

I would simply remove the donut element, perform your asort, and then add the donut item back on.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top