0

I have looked in other posts with the same problem but i cand find a solution for my problem...

I just want to sort this array:

private $text = array(
    array(1, 'aa', '11'),
    array(2, 'cc', '22'),
    array(3, 'bb', '33')
    );

but sorted by the second value, the string.

my code

class combo {  

    private $text = array(
    array(1, 'aa', '11'),
    array(2, 'cc', '22'),
    array(3, 'bb', '33')
    );


     public function combo() {

        //UPDATE WITH PERRYs ANSWER
        usort($this->text, function ($a, $b) {
            return $b[1] < $a[1];
        });

        $content='<div id="round">'.
                        '<div class="round1">'.
                                '<select>';
                                for( $i=0; $i<=3; $i++ )
                                {
                                    $content.= '<option value="' . utf8_encode($this->text[$i][0]) . '">' . utf8_encode($this->text[$i][1]) . '</option>';
                                }
                                $content.='</select>';   
                        $content.='</div>';                 
        $content.='</div>';
        return $content;   
    }


}

thanks!

Rafael S.

Rafael Spessotto
  • 81
  • 1
  • 4
  • 12

1 Answers1

1

You can use usort.

usort($text, function ($a, $b) {
    return $b[1] < $a[1];
});
Perry
  • 153
  • 6
  • Perry could you explain your answer? what is the $a and $b? – Rafael Spessotto Jul 26 '16 at 19:01
  • When you use a function to sort an array, PHP automatically defines `$a` and `$b` to that function with the values from the array. When you switch a and b, you will go from ascending to descending and vice versa. The `[1]` will get the second value from your array, in this case the `aa`, `bb` and `cc`. – Perry Jul 26 '16 at 19:04
  • gives me this error: Parse error: syntax error, unexpected T_FUNCTION in line 211 – Rafael Spessotto Jul 26 '16 at 19:12
  • You cannot use that function when you define the variable in the heading of the script. You'll need to place this somewhere else. – Perry Jul 26 '16 at 19:14
  • Perry ive updated my question with your answer...to show the entire code – Rafael Spessotto Jul 26 '16 at 19:23
  • Works fine for me. Maybe you made a typo somewhere? Only thing is that you'll get `undefined offset` errors because of `<= 3` instead of `< 3` – Perry Jul 26 '16 at 19:28