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

0

3 Answers 3

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. )

Sign up to request clarification or add additional context in comments.

7 Comments

Will the array_keys not just be "one", "tow", "three" since array_keys also returns strings?
@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 Yeah my bad. :-) gg
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 :)
@PederN )) Added this to the answer, then saw your comment. ) Anyway, good catch. )
|
1
$i = 0;
foreach( $array as $key => $value )
{
    $array[$key] = $i;
    $i++
}

Should do it :-)

Comments

0

You are probably looking for PHP asort().

1 Comment

He wants to renumber, not to sort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.