简体   繁体   English

如何按另一个数组的值对一个数组进行排序?

[英]How can I sort one array by the values of another array?

My array $a defines the sorting of my elements:我的数组 $a 定义了我的元素的排序:

array:4 [▼
  "rabbit" => "201"
  "cat" => "0"
  "monkey" => "100"
  "horse" => "0"
]

array $b defines a number:数组 $b 定义一个数字:

array:4 [▼
  "rabbit" => "9144"
  "cat" => "10244"
  "monkey" => "10068"
  "horse" => "9132"
]

I try to sort now the numbers by the sorting element.我现在尝试按排序元素对数字进行排序。 The result I am looking for is:我正在寻找的结果是:

   array:4 [▼
      1 => "9144"
      2 => "10068"
      3 => "10244"
      4 => "9132"
    ]

I try to achieve this with "array_combine":我尝试使用“array_combine”来实现这一点:

  $c=array_combine($a,$b);
  krsort($c);

But because of the zero I am loosing one element:但是由于零,我失去了一个元素:

array:3 [▼
  201 => "9144"
  100 => "10068"
  0 => "9132"
]

You want something along these lines:你想要一些类似的东西:

uksort($b, function ($i, $j) use ($a) {
    return $a[$i] <=> $a[$j];
});

This sorts $b by its keys, and the key values are translated to the numeric values in $a and compared by those.这会按其键对$b进行排序,并将键值转换为$a中的数值并与之进行比较。 This even keeps the key-value association in $b ;这甚至将键值关联保留在$b中; if you want to get rid of the keys you can use array_values() afterwards.如果你想摆脱键,你可以在之后使用array_values()

You can sort a copy of the first, keeping the associated keys.您可以对第一个副本进行排序,保留关联的键。 With asort .asort And then just loop that and build a new array with the mapped values from b.然后只需循环并使用来自 b 的映射值构建一个新数组。

<?php

$a = [
  "rabbit" => "201",
  "cat" => "0",
  "monkey" => "100",
  "horse" => "0"
];

$b = [
  "rabbit" => "9144",
  "cat" => "10244",
  "monkey" => "10068",
  "horse" => "9132"
];

$sort_order = $a;
asort($sort_order, SORT_DESC);
$i = 1;
foreach($sort_order as $k => $v)
    $result[$i++] = $b[$k];

var_dump($result);

Output: Output:

array(4) {
    [1]=>
    string(5) "10244"
    [2]=>
    string(4) "9132"
    [3]=>
    string(5) "10068"
    [4]=>
    string(4) "9144"
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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