0

I have the following array and i want to sort it by the number of every word.

Array ( [0] => Array ( [test] => 0 ) 
[1] => Array ( [test1] => 1296 ) 
[2] => Array ( [test2] => 1046 ) 
[3] => Array ( [test3] => 1171 ) 
[4] => Array ( [test4] => 857 ) 
[5] => Array ( [test5] => 1051 )
[6] => Array ( [test6] => 929 ) 
[7] => Array ( [test7] => 986 )

I want to produce Array ( [0] => Array ( [test1] => 1296 ) [1] => Array ( [test3] => 1171 ) etc...

2

1 Answer 1

1

Try the below function may be it will be helpful for you,

Use to below given function to sort the array of second element.

function sort_array_second_element($array) {
    $temp = array();
    foreach ($array as $key => $value) {
        foreach ($value as $key_new => $value_new) {
            $temp[] = $value_new;
        }
    }
    rsort($temp);
    $new_temp = array();
    foreach ($temp as $value) {
        foreach ($array as $value_new) {
            foreach ($value_new as $key_new => $value_temp) {
                if ($value == $value_temp) {
                    $new_temp[] = $value_new;
                }
            }
        }
    }
    return $new_temp;
}

Simple pass your current array in the given function like following:

$arr = array(
    array("test" => 0),
    array("test1" => 1296),
    array("test2" => 1046),
    array("test3" => 1171),
);

$sorted_arr = sort_array_second_element($arr);
print_r($sorted_arr);

This will generate the same output as you want.

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

1 Comment

Thanks, although if the number is the same for 2 records, it will add them to the array x2 times, both of them.

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.