سؤال

How to add element to begining array after asort() With keeping keys?

$array = array(
    564 => "plum",
    123 => "apple",
    543 => "lemon",
    321 => "cherry",
    );
    asort($array);
    $array[0]="all";
    print_r($array);

I get, index of key [0] is not at the beginig

Array(
[123] => apple
[321] => cherry
[543] => lemon
[564] => plum
[0] => all )

Need

Array(
[0] => all    
[123] => apple
[321] => cherry
[543] => lemon
[564] => plum)
هل كانت مفيدة؟

المحلول

$array = array(
    564 => "plum",
    123 => "apple",
    543 => "lemon",
    321 => "cherry",
);
$array[0]="all";
uasort($array, function($a, $b) {
  if ($a === 'all') return -1;
  return strcmp($a, $b);
});
print_r($array);

نصائح أخرى

After sorting your array, use array_unshift() to prepend elements to the beginning of the array.

array_unshift($arr, 'all')

Update:

Note that array_unshift() will modify all numerical keys. To preserve the keys, use the + operator.

asort($array);
$array = array('all') + $array;
print_r($array);

/*
Array
(
    [0] => all
    [123] => apple
    [321] => cherry
    [543] => lemon
    [564] => plum
)
*/

Call asort() after adding values to the array. If you can guarantee the items that need to be added are already in reverse order and always come before the items already in the array, then you can use $array = array($newitem) + $array.

$array = array(
    564 => "plum",
    123 => "apple",
    543 => "lemon",
    321 => "cherry",
);
$array[0]="all";
asort($array);
print_r($array);

Output:

Array
(
    [0] => all
    [123] => apple
    [321] => cherry
    [543] => lemon
    [564] => plum
)

This will also work when adding items that do not come before apple.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top