如何使用另一个数组中的键重新排序数组?

时间:2013-05-29 19:38:11

标签: php arrays

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

要重新订购的数组:

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
)

2 个答案:

答案 0 :(得分: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
        )

)

答案 1 :(得分: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);