useless-stuff
2/12/2016 - 2:42 PM

PHP - ArrayIterator

PHP - ArrayIterator

<?php

// Example 1, alphabetic order
$availableServices = ['Building a website', 'SEO', 'SEM', 'Logo design', 'Mobile applications'];
$servicesCollection = new ArrayIterator($availableServices);
$servicesCollection->natsort();
foreach ($servicesCollection as $service) {
    print_r((array)$service);
}
/*
[
    {
        0: "Building a website"
    },
    {
        0: "Logo design"
    },
    {
        0: "Mobile applications"
    },
    {
        0: "SEM"
    },
    {
        0: "SEO"
    }
]
 */

// Example 2, numeric order, get ordered vehicles in a parching.

/**
 * Class Car
 */
class Car
{

    protected $numberPlate;

    /**
     * @return mixed
     */
    public function getNumberPlate()
    {

        return $this->numberPlate;
    }

    /**
     * @param mixed $numberPlate
     */
    public function setNumberPlate($numberPlate)
    {

        $this->numberPlate = $numberPlate;
    }
}

/**
 * Class ParkedCar
 */
class ParkedCar extends Car
{

    protected $carPosition;

    /**
     * @return mixed
     */
    public function getCarPosition()
    {

        return $this->carPosition;
    }

    /**
     * @param mixed $carPosition
     */
    public function setCarPosition($carPosition)
    {

        $this->carPosition = $carPosition;
    }

    /**
     * @return string
     */
    public function __toString()
    {

        return (string)'Position: '.$this->carPosition.' - Plate: '.$this->getNumberPlate();
    }

}

/**
 * Class Parking
 */
class Parking extends ArrayIterator
{

    public function getCarsPosition()
    {

        $this->natsort();

        return $this;
    }
}

// Generate random data
$parking = new Parking();
for ($i = 1; $i < 11; $i++) {
    $car = new ParkedCar();
    $car->setNumberPlate(substr(md5(microtime()), 0, 8));
    $car->setCarPosition(rand(0, 9999));
    $parking->append($car);
}


foreach ($parking->getCarsPosition() as $parkedCar) {
    /** @var ParkedCar $car */
    echo nl2br($parkedCar.PHP_EOL);
}

/*
Random output:
Position: 1819 - Plate: d8b15589
Position: 2278 - Plate: 9b70ad76
Position: 2509 - Plate: f306b5df
Position: 2816 - Plate: 04ce1846
Position: 3085 - Plate: 9539d29f
Position: 4519 - Plate: ae149aad
Position: 5906 - Plate: 67612043
Position: 7133 - Plate: a6490ca3
Position: 7340 - Plate: 3fa86f38
Position: 7738 - Plate: 79528a17
*/