-1

I've been trying to write a recursive function that would reorder an array of objects based on the order provided by another array (simple, numeric array).

I want to use this sorting function to sort an array of objects by a 'template' array that would hold only one property of each object present in the array to sort, e.g.

$template = ['A', 'B', 'C']

Array to sort:

$myArray = [
    new Element('B'),
    new Element('C'),
    new Element('A'),
]

class Element
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

I was not successful. Perhaps you might have an idea about how to apprach this task?

luqo33
  • 8,001
  • 16
  • 54
  • 107
  • Take a look here : http://stackoverflow.com/questions/4501340/order-multidimensional-array-recursively-at-each-level-in-php I think it's similar to your problem – EL OUFIR Hatim Oct 01 '15 at 21:09
  • Is there a reason why it has to be a recursive function and why you can't use any of PHP's sorting functions? – georaldc Oct 01 '15 at 21:20
  • @georaldc, Yes, I want to adapt this function to sort an array of objects based on the template array where the template array would hold only one property of objects stored in the array to sort. I will edit my question to make it clear. – luqo33 Oct 01 '15 at 21:22

2 Answers2

1

I don't see how recursion would help you with that task. This is how you can use the built in sort functions:

usort($myArray, function(Element $a, Element $b) use ($template) {
    return array_search($a->name, $template) - array_search($b->name, $template);
});
  • usort sorts by given comparison callback
  • I added the Element type hint to the callback because the sort function will only work with arrays of Element objects
  • array_search returns the key for the given name property value within the $template array. If the value does not exist in the array, it will be placed at the beginning, because the result false is coerced to 0.
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
  • This is a great, compact way to do it. There is no particular reason why it'd have to be a recursive function, really. – luqo33 Oct 02 '15 at 07:26
0

I also managed to do the sorting using recursion - here it is:

function orderRecursively($template, $myArray, &$ordered)
{
    foreach($myArray as $k => $v) {
        if ($myArray[$k]->name == $template[0]) {
            $ordered[] = $myArray[$k];
            array_splice($template, 0, 1);
        }
    }
    if (!empty($template)) orderRecursively($template, $myArray, $ordered);
}

$ordered = [];
order($template, $myArray, $ordered);

$ordered would then hold the sorted array of objects. Still, I find @fschmengler's answer more elegant.

luqo33
  • 8,001
  • 16
  • 54
  • 107