-3

根据另一个数组中的值重新排序数组的最佳方法是什么?

要重新排序的数组:

Array
(
    [0] => Array
        (
            [full_name] => Graham Smith
        )

    [1] => Array
        (
            [full_name] => Gerry Jones

        )

    [2] => Array
        (
            [full_name] => Frank Brown
        )

)

订单数组:

(
    [0] => Jones
    [1] => Brown
    [2] => Smith
)
4

2 回答 2

1

这是一种非常天真、直接的方法来做你想做的事

<?php

$array = array(
    array("full_name" => "Jack"),
    array("full_name" => "Bob"),
    array("full_name" => "Graham Smith"),
    array("full_name" => "Gerry Jones"),
    array("full_name" => "Frank Brown")
);

$order = array(
    "Jones",
    "Brown",
    "Smith"
);

function findOrderPosition($term) {
    global $order;

    for ($i = 0; $i < sizeof($order); $i++) {
        if ($term == $order[$i])
            return $i;
    }

    return -1;
}

usort($array, function($a, $b) {
    //Get the last names here (checking only the last space delimited token).
    $arra = explode(' ', $a['full_name']);
    $arrb = explode(' ', $b['full_name']);

    //Find the position in the $order array.
    $posa = findOrderPosition($arra[sizeof($arra) - 1]);
    $posb = findOrderPosition($arrb[sizeof($arrb) - 1]);

    if ($posa == -1) {
        return 1; //Couldn't find item $a in the order array, so we want to move $b ahead of it.
    }

    if ($posb == -1) {
        return -1; //Couldn't find item $b in the order array, so we want to move it to the bottom of the array.
    }

    if ($posa == $posb) {
        return 0; //Don't move the item up or down if they are equal.
    }

    return $posa > $posb ? 1 : -1; //If position of $a is greater than $b then we want to move $a up, otherwise, move it down.
});

print_r($array);

输出

Array
(
    [0] => Array
        (
            [full_name] => Gerry Jones
        )

    [1] => Array
        (
            [full_name] => Frank Brown
        )

    [2] => Array
        (
            [full_name] => Graham Smith
        )

    [3] => Array
        (
            [full_name] => Jack
        )

    [4] => Array
        (
            [full_name] => Bob
        )

)
于 2013-05-29T19:59:01.983 回答
0

我发现这个解决方案更容易理解,尽管我不知道哪种解决方案效果最好。

$array = array(
    array("full_name" => "Jack"),
    array("full_name" => "Bob"),
    array("full_name" => "Graham Smith"),
    array("full_name" => "Gerry Jones"),
    array("full_name" => "Frank Brown")
);

$order = array(
    "Jones",
    "Brown",
    "Smith"
);

$array_ordered = array();
$x = 0;
foreach ($order as &$find) {
    foreach ($array as $key => $row) { 
        $pos = strpos($row['full_name'], $find);
        if ($pos)  {
            $array_ordered[$x] = $array[$key];
        }
    }
    $x++;
}
print_r($array_ordered);
于 2013-05-30T09:06:14.940 回答