pablo-sg-pacheco
9/22/2016 - 10:07 PM

Order an multidimensional array based on another array

Order an multidimensional array based on another array

<?php

/*
$terms = 
Array
(
    [2] => WP_Term Object
        (
            [term_id] => 6
        )

    [1] => WP_Term Object
        (
            [term_id] => 5
        )

    [0] => WP_Term Object
        (
            [term_id] => 3
        )

)

$originalTerms = 
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 6
        )

    [1] => WP_Term Object
        (
            [term_id] => 5
        )

    [2] => WP_Term Object
        (
            [term_id] => 3
        )

)
*/

usort($terms, function($a, $b) use ($originalTerms) {
	$keyA = array_search($a->term_id, array_column(array_map(function($o){return (array)$o;},$originalTerms),'term_id'));
	$keyB = array_search($b->term_id, array_column(array_map(function($o){return (array)$o;},$originalTerms),'term_id'));
	return ($keyA<$keyB) ? -1 : 1;
});