[英]How to swap array elements in php?
I have an array 我有一个数组
Array
(
[0] => Array
(
[order_id] => 1318
[code] => shipping
[title] => UK Shipping (Weight: 0.00kg)
[value] => 10.2000
)
[1] => Array
(
[order_id] => 1318
[code] => sub_total
[title] => Sub-Total
[value] => 4.7000
)
[2] => Array
(
[order_id] => 1318
[code] => coupon
[title] => Coupon (10P)
[value] => -0.4700
)
[3] => Array
(
[order_id] => 1318
[code] => tax
[title] => VAT (20%)
[value] => 2.8860
[sort_order] => 8
)
[4] => Array
(
[order_id] => 1318
[code] => total
[title] => Total
[value] => 17.3160
)
)
I want to swap the array index. 我想交换数组索引。 I want to swap the array index when [code] => coupon to [code] => sub_total, If coupon is available. 我想在[code] => coupon转换为[code] => sub_total时交换数组索引(如果有coupon)。 I want the position of coupon to above the subtotal. 我希望优惠券的位置在小计之上。 I want the position of sub_total to above the vat. 我希望将sub_total的位置设置在大桶上方。 How is it possible? 这怎么可能? Please help me. 请帮我。
You can define a custom sort order array that puts each of the possible values of code
in the order you want. 您可以定义一个自定义的排序顺序数组,该数组将每个可能的code
值按所需的顺序放置。
$custom_sort_order = array(
'shipping' => 1,
'coupon' => 2,
'sub_total' => 3,
'tax' => 4,
'total' => 5);
then you can use that custom sort order in the comparison function of usort
to get the array items in your desired order. 那么您可以在usort
的比较功能中使用该自定义排序顺序,以按所需顺序获取数组项。
usort($your_array, function($x, $y) use ($custom_sort_order) {
// find the sort number for each item
$x = $custom_sort_order[$x['code']];
$y = $custom_sort_order[$y['code']];
// do the comparison
if ($x == $y) return 0;
return $x - $y;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.