문제

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