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

mardav
  • 57
  • 8
  • Use `array_filter`. Check this http://php.net/manual/en/function.array-filter.php – Virb May 05 '18 at 12:28
  • 3
    Possible duplicate of [How to sort an array of associative arrays by value of a given key in PHP?](https://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php) – Emad Elpurgy May 05 '18 at 13:22

1 Answers1

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.

Jaydip Shingala
  • 429
  • 2
  • 11
  • 18
  • Thanks, although if the number is the same for 2 records, it will add them to the array x2 times, both of them. – mardav May 09 '18 at 09:36