K. B.
K. B.

Reputation: 1430

Sort multidimensional array by value which contain numbers and words

I have an multidimensional array and need to sort it by values. When I try to sort it I get that print_r() result.

[0] => Array
        (
            [name] => Memory
            [attribute_values] => Array
                (
                    [0] => Array
                        (
                            [name] => test 1
                            [values] => Array
                                (
                                    [0] => 1 Port
                                    [1] => 10 Port s
                                    [2] => 2 Port w
                                    [3] => 3 Port D
                                    [4] => 5
                                )

                        )

                )

        )

I need to get like this:

                    [values] => Array
                        (
                            [0] => 1 Port
                            [1] => 2 Port w
                            [2] => 3 Port D
                            [3] => 5
                            [4] => 10 Port s
                        )

The text in values can be very different, but i Need to sort it by numbers in ASC and DESC. It is possible?

Upvotes: 1

Views: 30

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94662

Use a Natural Sort natsort()

$tst = ['1 Port', '10 Port s', '2 Port w', '3 Port D', '5'];

natsort($tst);
print_r($tst);

RESULT

Array
(
    [0] => 1 Port
    [2] => 2 Port w
    [3] => 3 Port D
    [4] => 5
    [1] => 10 Port s
)

Upvotes: 2

Related Questions