Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

How to sort an array of classes that contain nested classes using custom comparison logic in PHP

1 Answer

0 votes
<?php

class Address {
    public string $city;
    public int $zip;

    public function __construct(string $city, int $zip) {
        $this->city = $city;
        $this->zip = $zip;
    }
}

class Person {
    public string $name;
    public int $age;
    public Address $address;

    public function __construct(string $name, int $age, Address $address) {
        $this->name = $name;
        $this->age = $age;
        $this->address = $address;
    }
}

function printPersons(array $people): void {
    foreach ($people as $p) {
        echo "{$p->name} | age: {$p->age} | city: {$p->address->city} | zip: {$p->address->zip}\n";
    }
}

function sortPersons(array &$people): void {
    usort($people, function(Person $a, Person $b) {
        if ($a->address->city !== $b->address->city) {
            return $a->address->city <=> $b->address->city;
        }
        if ($a->address->zip !== $b->address->zip) {
            return $a->address->zip <=> $b->address->zip;
        }
        return $a->age <=> $b->age;
    });
}

$people = [
    new Person("Alice", 30, new Address("San Francisco", 42100)),
    new Person("Bob",   40, new Address("Austin",        32000)),
    new Person("Carol", 35, new Address("New York City", 42000)),
    new Person("Dave",  25, new Address("Austin",        32000)),
    new Person("Eve",   28, new Address("New York City", 61000)),
];

sortPersons($people);
printPersons($people);



/*
run:

Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100

*/

 



answered Sep 1 by avibootz
edited Sep 1 by avibootz

Related questions

...