PHP重新排列数组元素

时间:2014-12-15 06:53:42

标签: php arrays sorting

我有一个动态使用key作为表头的数组,我想按此顺序重新排列以下内容:

fullname, age, email, tel, project, type, purpose, budget, income 

默认数组元素

Array
(
    [type] => Plastic
    [purpose] => Sell
    [budget] => 401,000-500,000
    [income] => 12,000-29,999
    [fullname] => John Smith
    [age] => 30
    [email] => john@email.com
    [tel] => 12345678
    [project] => Project A
)

可以在代码中手动move完成吗?

4 个答案:

答案 0 :(得分:0)

请查看以下链接

Sort an Array by keys based on another Array?

它用于使用另一个数组重新排序

function sortArrayByArray(Array $array, Array $orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

在上面的链接

中检查此功能

答案 1 :(得分:0)

$arr = array();// THIS IS YOUR INPUT ARRAY.
$sort = array('fullname', 'age', 'email', 'tel', 'project', 'type', 'purpose', 'budget', 'income');
$n = array();
foreach ($sort as $v) {
  $n[$v] = $arr[$v];
}
echo '<pre>';
print_r($n);
echo '</pre>';

注意:这是一个示例,您也可以在循环中应用它。

Working Example

答案 2 :(得分:0)

其中$original_data是包含您在问题中列出的数组的变量,您可以使用此逻辑根据一组列名对其进行重新排序:

$new_sort_order = array(
    'fullname',
    'age',
    'email',
    'tel',
    'project',
    'type',
    'purpose',
    'budget',
    'income',
);

$sorted_data = array();
foreach ($new_sort_order as $column_title) {
    if(isset($original_data[$column_title])) {
        $sorted_data[$column_title] = $original_data[$column_title];
    }
}

var_export($sorted_data);

答案 3 :(得分:0)

将所需的键顺序放在一个数组中,并在该键数组中放置forete项,从旧数组中放置其各自的内容。最后,新数组将按$ arr中提到的顺序排列。

//$oldArr
Array 
    (
        [type] => Plastic
        [purpose] => Sell
        [budget] => 401,000-500,000
        [income] => 12,000-29,999
        [fullname] => John Smith
        [age] => 30
        [email] => john@email.com
        [tel] => 12345678
        [project] => Project A
    )

$ oldArr包含key =&gt;如上所述的值数组

$arr = array('fullname','age','email','tel','project','type','purpose','budget','income');
foreach($arr as $a)
{
   if($oldArr[$a])
    $newArr[$a] = $oldArr[$a];
}