Search code examples
phparrayssorting

PHP Natural sort on array of objects by a column


I am having a few issues sorting an array. I make a call to an API and the data I get back is like so

array:41 [
  0 => StreetData {#251
    +house: "1 Some Street"
    +street: ""
  }
  1 => StreetData {#236
    +house: "11 Some Street"
    +street: ""
  }
  2 => StreetData {#236
    +house: "4 Some Street"
    +street: ""
  }
]

I am trying to do a natural sort so been trying

ksort($address->streets);

This does not seem to change anything. What I am after is basically a natural search. So numbers should be considered first, and then the street. So for the above, I would expect it to be

array:41 [
  0 => StreetData {#251
    +house: "1 Some Street"
    +street: ""
  }
  1 => StreetData {#236
    +house: "4 Some Street"
    +street: ""
  }
  2 => StreetData {#236
    +house: "11 Some Street"
    +street: ""
  }
]

As 11 is greater than 4. This is a pretty vague example, obviously I expect there to be a 2, 3 etc.

So how can I achieve this natural type of sorting?


Solution

  • I think you need strnatcmp and usort.

    <?php
        class StreetData
        {
            public $house;
            public $street;
    
            public function StreetData($a, $b)
            {
                $this->house = $a;
                $this->street = $b;
            }
        }
    
        $arr = array(
            new StreetData("1 Some Street", ""),
            new StreetData("11 Some Street", ""),
            new StreetData("4 Some Street", ""),
        );
    
        function mySort($a, $b)
        {
            return strnatcmp($a->house, $b->house);
        }
    
        usort($arr, "mySort");
    
        var_dump($arr);
    ?>