1

Using CakePHP 2.7, I have an array of find results:

array(
    (int) 0 => array(
        'Foo' => array(
            'id' => '786',
            'bar_id' => '12',
            // more data
        ),
        'Bar' => array(
            'id' => '12',
            // more data
        )
    ),
    (int) 1 => array(
        'Foo' => array(
            'id' => '785',
            'bar_id' => '13',
            // more data
        ),
        'Bar' => array(
            'id' => '13',
            // more data
        )
    ),
    // many more results

Now I want do have it sorted by 'bar_id' in a defined individual way, not numeric. The sort order is described in another array:

array(9, 3, 18, 36, …)

Is there a better way to do it but to loop over the sort array, pick the current id then loop over the results array (a loop within a loop), look there for the corresponding 'bar_id' and if found write the result into a new results array?

$results = array(…); // the results
$order = array(9, 3, 18, 36, …);
$sortedResults = array();
foreach ($order as $barId) {
    foreach ($results as $result) {
        if ($barId == $result['Foo']['bar_id']) {
            $sortedResults[] = $result;
            break;
        }
    }
}

I know that Cake has the Hash utility (formerly 'Set') to work with arrays, but I couldn't find a way to do it with Has.

1 Answer 1

1

I would do this way:

$indexed_results = Hash::combine($results , '{n}.Foo.bar_id', '{n}');

foreach($order as $index)
{
    $sortedResults[] = $indexed_results[$index];
}

the first row replaces the index in $results with the corrispondant value of bar_id so you can do a single loop

edit: probably you'll have to check that the $index actually exists in your array unless you're sure that every value in $order has a correspondent bar_id otherwise you'll get a "Undefined index" notice

1
  • Thank you, arilia. It works just fine! I'm sorry, my reputation is not high enough to vote up your answer.
    – Christian
    Commented Jan 13, 2016 at 13:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.