我目前正在尝试根据另一个数组的值来排序数组。这些值是唯一的。我看到了如何基于另一个数组的键来排序数组的示例,但我似乎无法找到一个通过另一个数组的值专门对数组进行排序的示例。两个数组都具有相同的值。一个数组有一个额外的键id
。我怎么能实现这一目标?
按顺序排列的数组:
Array
(
[0] => Array
(
[src] => 2GK2VWE-ax--0
)
[1] => Array
(
[src] => 13KXEXyJaM9-0
)
[2] => Array
(
[src] => 138XELryjM9-0
)
)
要订购的数组:
Array
(
[0] => Array
(
[src] => 13KXEXyJaM9-0
[id] => 123468
)
[1] => Array
(
[src] => 138XELryjM9-0
[id] => 15784239
)
[2] => Array
(
[src] => 2GK2VWE-ax--0
[id] => 12558456
)
)
所需订单:
Array
(
[0] => Array
(
[src] => 2GK2VWE-ax--0
[id] => 12558456
)
[1] => Array
(
[src] => 13KXEXyJaM9-0
[id] => 123468
)
[2] => Array
(
[src] => 138XELryjM9-0
[id] => 15784239
)
)
答案 0 :(得分:1)
您无需对数组进行排序。只需从“要排序的数组”中搜索src,然后在原始数组中添加id。
cust = Customer.arel_table
prod = ProductCategory.arel_table
TotalSales.joins(:customer).includes(:product_category).
where(cust[:organization_id].eq(1)).
group(cust[:external_id], prod[:external_id]).
maximum(:start_date)
输出:
$originalArray = [
[
'src' => '2GK2VWE-ax--0'
],
[
'src' => '13KXEXyJaM9-0'
],
[
'src' => '138XELryjM9-0'
]
];
$sortedArray = [
[
'src' => '13KXEXyJaM9-0',
'id' => 123468
],
[
'src' => '138XELryjM9-0',
'id' => 15784239
],
[
'src' => '2GK2VWE-ax--0',
'id' => 12558456
]
];
$src = array_column($originalArray, 'src');
foreach ($sortedArray as $data) {
if (false !== $key = array_search($data['src'], $src)) {
$originalArray[$key]['id'] = $data['id'];
}
}
var_dump($originalArray);