-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?

3
  • Take a look here : stackoverflow.com/questions/4501340/… I think it's similar to your problem Commented Oct 1, 2015 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? Commented Oct 1, 2015 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. Commented Oct 1, 2015 at 21:22

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

This is a great, compact way to do it. There is no particular reason why it'd have to be a recursive function, really.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.