-3

Possible Duplicate: PHP custom sorting

I have an array,

Array
(
    [Flag]      =>  2
    [Pending]   => 11
    [Received]  => 11
    [Sent]      =>  8
    [Skip]      =>  5
    [Complaint] =>  1
    [Query]     =>  1
)

I have two requests for the above array:

  1. How can I sort this into the order Received, Sent, Pending, Flag, Skip, Query, Request, Complaint.

  2. As we see that "Request" is not available in the array, how do I push it into the array with the value zero?

3
  • 2
    What have you tried? I recommend you read about usort() which is User Defined sorting: php.net/manual/en/function.usort.php Commented Nov 6, 2012 at 16:53
  • to do sorting like thatyou have to do manually there is not any also for that Commented Nov 6, 2012 at 16:53
  • What way are you creating the array? Commented Nov 6, 2012 at 16:53

3 Answers 3

1
$array = array
(
    "Flag" => 2
    "Pending" => 11
    "Received" => 11
    "Sent" => 8
    "Skip" => 5
    "Complaint" => 1
    "Query" => 1
);

$array["Request"] = 0;

function my_sort($a, $b) {
    $order = array("Received", "Sent", "Pending", "Flag", "Skip", "Query", "Request", "Complaint");
    return array_search($b, $order) - array_search($a, $order);
}

uksort($array, "my_sort");

print_r($array);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! that helped however it processed Array ( [0] => 1 [1] => 1 [2] => 5 [3] => 8 [4] => 11 [5] => 11 [6] => 2 ) and values were lost... how can i maintain the values?
Ah, use uksort instead
0

Try usort, followed by,

$array['Request'] = 0;

Comments

0

With the PHP function usort(), you can create a user-defined function and sort your array based on the results of this function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.