根据键的值对数组进行排序

时间:2012-07-18 01:17:35

标签: php

我有一个具有正确顺序的数组, 例如,

$array_keysorder=([0]=>"Fire",[1]=>"Sky",[2]=>"Third")

//Array i want to sort,after appending the order is messed up
$tosortarray=(['Sky']=>array(array()...),['Third']=>array(),['Fire']=>array())

//This is how i want the final array to look like 
$Final=(['Fire']=>array(), ['Sky']=>array(array()...),['Third']=>array())

1 个答案:

答案 0 :(得分:0)

重建阵列怎么样?

编辑..我添加了一些评论..

<?php
$array_keysorder[] = "Fire";
$array_keysorder[] = "Sky";
$array_keysorder[] = "Third";

print_r($array_keysorder);

$bad_array[Sky] = "data1";
$bad_array[Third] = "data2";
$bad_array[Fire] = "data3";

echo "<br>";
print_r($bad_array);

//This count cycles through the sort order, 0 = Fire, 1 = Sky, etc.
$key = 0;

//Cycle through array. $row isn't used.
foreach($bad_array as $row)
{
    //$temp_val will store the key name ie "Fire".
    $temp_val = $array_keysorder[$key];
    //Create a organized array with the correct order of the keys
    $good_array[$temp_val] = $bad_array[$temp_val];
    //Increase the key to the next one.
    $key++;
}

echo "<br>";
print_r($good_array);
?>