Skip to content
Advertisement

Sorting an associative array with a string in PHP

I’m working on a php issue with an associative array and attempting to sort it. What I have looks something like this:

[2021-07-16T10:45:23-04:00] => Array
    (
        [0] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples
        [1] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Apples
        [2] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [3] => 0.0.0.111|83b5ed42d2593aa37ad8c428e4f76288|Oranges
    )

[2021-07-16T10:45:24-04:00] => Array
    (
        [0] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples
        [1] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples
        [2] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [3] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [4] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Oranges
        [5] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Apples
        [6] => 0.0.0.111|83b5ed42d2593aa37ad8c428e4f76288|Apples
    )

I want to sort it so it looks like this:

[2021-07-16T10:45:23-04:00] => Array
    (
        [0] => 0.0.0.111|83b5ed42d2593aa37ad8c428e4f76288|Oranges
        [1] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Apples
        [2] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [3] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples
    )

[2021-07-16T10:45:24-04:00] => Array
    (
        [0] => 0.0.0.111|83b5ed42d2593aa37ad8c428e4f76288|Apples
        [1] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [2] => 0.0.1.177|278670a3934717e4c005e02b9a4c1bab|Apples
        [3] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Oranges
        [4] => 0.0.0.133|631dad007000b9ed59d41653176ac04b|Apples
        [5] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples
        [6] => 0.0.1.222|ed7e434b79e54834440101fc07cc0981Apples
    )

I’ve thought about exploding along the | and then taking the 0.0.0.111 and comparing it to everything else. What I tried look like this:

  foreach ($test_array as $info) {
    asort($info);
  }

I realized though that I comparing the whole: 0.0.1.222|ed7e434b79e54834440101fc07cc0981|Apples

instead of the first part 0.0.1.222. Thank you for any help.

Advertisement

Answer

Try array_map('sort', $yourMainArray); or run your own callback on the map or even a simple loop and sort would do it.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement