1

is there any way to reorder values in array? for example i have

 Array (
    "one" => 0,
     "tow" => 0,
     "three" => 0,
     "four" => 8,
     "apple" => 4,
     "pink" => 3,
   );

and convert it to

 Array (
    "one" => 0,
     "tow" => 1,
     "three" => 2,
     "pink" => 3,
     "apple" => 4,
     "four" => 5,
   );

EDIT:

please notice that "four" has bigger value it should change to 5 and "apple" & "pink" should not change

h0mayun
  • 3,466
  • 31
  • 40

3 Answers3

6

How about as simple as...

$source  = array('one' => 0, 'tow' => 0, 'three' => 0, 'four' => 8, 'apple' => 4, 'pink' => 3);
asort($source);
$result  = array_flip(array_keys($source));

Explanation: array_keys will collect all the keys of your original array as another, indexed array, and array_flip will just turn these indexes into values. )

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Will the array_keys not just be "one", "tow", "three" since array_keys also returns strings? – Jonas m Dec 19 '12 at 11:59
  • 1
    @Jonasm The result of array_keys will look like `array(0 => 'one', 1 => 'tow', 2 => 'three')`. array_flip will, well, flip this array, so it becomes `('one' => 0, 'tow' => 1, 'three' => 2)`: keys turn to values, values turn to keys. ) – raina77ow Dec 19 '12 at 12:00
  • @raina77ow Yeah my bad. :-) gg – Jonas m Dec 19 '12 at 12:02
  • He wanted it sorted before the flip, note that `four` is in another position in the second array. Add that and I think that this answer is a winner :) – MrKiane Dec 19 '12 at 12:05
  • 1
    @PederN )) Added this to the answer, then saw your comment. ) Anyway, good catch. ) – raina77ow Dec 19 '12 at 12:07
  • please notice that "four" has bigger value, it should be 5 not the 'pink' – h0mayun Dec 19 '12 at 12:09
  • @h0mayun No, it works exactly like that. There's another pitfall here with no easy workarounds: PHP sorting functions do not provide stable sorting: when two elements of the original array have the same value, their ordering in the resulting array is undefined. Check [this thread](http://stackoverflow.com/questions/4353739/preserve-key-order-stable-sort-when-sorting-with-phps-uasort) for the replacement function, if that's an issue in your case. – raina77ow Dec 19 '12 at 12:17
1
$i = 0;
foreach( $array as $key => $value )
{
    $array[$key] = $i;
    $i++
}

Should do it :-)

Jonas m
  • 2,646
  • 3
  • 22
  • 43
0

You are probably looking for PHP asort().