F
F
Friend2021-07-08 00:23:53
PHP
Friend, 2021-07-08 00:23:53

How to sort a line consisting of numbers with a separator?

there is an array of strings

10/22/300
10/21/300
9/5/5/6

need to make it happen

9/5/5/6
10/21/300
10/22/300


That is, sorting should be by all data consisting of a substring. And nesting can be unlimited.

It is clear that in order to get these substrings, you need to use the command
$element = explode('/', $item);

First element, for example, it will turn into
[9,5,5,6]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
N, 2021-07-08
@Utarzan123

Even I didn’t understand ... so it doesn’t work?

<?php

$ar = [
    '10/22/300',
    '10/21/300',
    '9/5/5/6'
    ];

natsort($ar);

print_r($ar);

/* RESULT

Array
(
    [2] => 9/5/5/6
    [1] => 10/21/300
    [0] => 10/22/300
)

*/

A
Alexey, 2021-07-08
@alexeyshi

If I understood the problem correctly, then you can try this:

$array = [
    '10/22/300',
    '10/21/300',
    '9/5/5/6'
];

usort($array, function($a, $b) {
    $a = array_sum(explode('/', $a));
    $b = array_sum(explode('/', $b));
    return ($a == $b ? 0 : ($a < $b ? -1 : 1));
});

print_r($array);

The idea is that we sort by the sum of the numbers obtained from each line.
But you need to test on more examples.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question