0

I have the following array (hence the order, it is not exactly incremental)

array ( 4334 => '4334',
        4335 => '4335',
        4333 => '4333',
        4338 => '4338',
)

And this array

array ( 
        'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
        'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
        'charlie' => array ( 4334 => '4334', 'objects' => array ( ), 
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
)

As we can see, the second array contains 4 arrays. Inside there is an id again, e.g. alpha has 4333. How can I sort the second array, whereas the order is the same as the first plain array by id?

The final ordering should be:

array (
        'charlie' => array ( 4334 => '4334', 'objects' => array ( ),
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
        'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
        'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
)
1

1 Answer 1

1

Here is what worked for me:

function elementScore($element, $sorting_array)
{
    // get the first element and find its position in the sorting array.
    return $sorting_array[intval(array_values($element)[0])];
}

$array1 = array ( 4334 => '4334',
    4335 => '4335',
    4333 => '4333',
    4338 => '4338',
);
// get the values without the keys and flip keys and values.
$sorting_array = array_flip(array_values($array1));

$array2 = array (
    'alpha' => array ( 4333 => '4333', 'objects' => array ( ), ),
    'bar' => array ( 4338 => '4338', 'objects' => array ( ), ),
    'charlie' => array ( 4334 => '4334', 'objects' => array ( ),
        'delta' => array ( 4335 => '4335', 'objects' => array ( ), ), ),
);

// sort based on the score function.
uasort($array2, function ($a, $b) use (&$sorting_array) {
    return elementScore($a, $sorting_array) > elementScore($b, $sorting_array);
});
Sign up to request clarification or add additional context in comments.

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.