dongzhabo2796 2015-02-02 00:22
浏览 26
已采纳

通过索引数组重新排列数组 - PHP

I have an array of $Percentages1 that I have ordered in descending order using arsort() and then I have taken an array containing the new key order using array_keys() called $keyorder

My question is how do I now rearrange another array $Percentages2 into the same key order as $Percentages1?

Any help will be greatly appreciated, thanks very much!

Edit - Code as requested:

//$Percentages1 before sort for example =
// Array ( [0] => 5.10 [1] => 1.52 [2] => 8.42 [3] => 1.11 [4] => 1.35 )
arsort($Percentages1);
//$Percentages1 after sort =
// Array ( [2] => 8.42 [0] => 5.10 [1] => 1.52 [4] => 1.35 [3] => 1.11 )
$keyorder = array();
//So $keyorder is =
// Array ( [0] => 2 [1] => 0 [2] => 1 [3] => 4 [4] => 3 )
$keyorder = array_keys($Percentages1);

//Now I want to do something here to rearrange a $Percentages2 array
//in the same index order as $keyorder.
//For example from this
// Array ( [0] => 2.50 [1] => 3.52 [2] => 9.42 [3] => 9.81 [4] => 0.35 )
//To...
// Array ( [2] => 9.42 [0] => 2.50 [1] => 3.52 [4] => 0.35 [3] => 9.81 )
  • 写回答

1条回答 默认 最新

  • duanhong4274 2015-02-02 00:46
    关注

    If you are not adverse to creating another array variable, the simplest course here is just to loop over $keyorder and append the elements at the corresponding key from $Percentages2 onto a new array;.

    // Sorted as you already have it...
    $keyorder = array_keys($Percentages1);
    // Final array
    $output = array();
    foreach ($keyorder as $key) {
      $output[$key] = $Percentages2[$key];
    }
    
    // Don't need the source anymore
    unset($Percentages2);
    

    Their key order as appended onto $output will be retained in the final result.

    Given your input arrays, this produces

    print_r($output);
    Array
    (
        [2] => 9.42
        [0] => 2.5
        [1] => 3.52
        [4] => 0.35
        [3] => 9.81
    )
    

    You actually don't need to use array_keys(). Following the call to arsort(), you can foreach over the sorted $Percentages1 and sort to $output by key:

    // Skip array_keys, and read the sorted array directly
    arsort($Percentages1);
    foreach ($Percentages1 as $key => $value) {
      // Same as before inside the loop
      $output[$key] = $Percentages2[$key];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line