简体   繁体   中英

Sort array according to value of key

I have one array which have the right order of the keys, For example,

$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())

What about rebuilding the array?

Edit.. I added some commenting..

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM