开发者

Array Sorting using array

开发者 https://www.devze.com 2023-04-06 18:46 出处:网络
$sortP开发者_开发百科attern= array(1,2,8,4); $toSort = array(2,4,8,18,16,26); Now, we have to sort $toSort array according to $sortPattern.
$sortP开发者_开发百科attern= array(1,2,8,4);
$toSort = array(2,4,8,18,16,26);

Now, we have to sort $toSort array according to $sortPattern.

We should have the result

$result = array(2,8,4,18,16,26);

Does anyone know the function to do this, or should we have to write our own function to perform this?


Yes, you would have to write your own sort function, and apply it with usort(). In your callback, you would do something like:

if ( $a == $b ) {
    return 0;
} elseif ( array_search( $a, $sortPattern ) < array_search( $b, $sortPattern ) {
    return -1;
} else {
    return 1;
}


What influence does $sortPattern have on $toSort ?

It looks like maybe:

$result = array_merge(
    array_intersect($sortPattern, $toSort), // 2, 8, 4
    array_diff($toSort, $sortPattern)       // 18, 16, 26
);
0

精彩评论

暂无评论...
验证码 换一张
取 消