如何在php中交换数组元素


How to swap array elements in php?

我有一个数组

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

我想交换数组索引。我想在[code]=>优惠券到[code]=>sub_total时交换数组索引,如果优惠券可用。我希望优惠券的位置在小计之上。我希望sub_total的位置在大桶上方。这怎么可能?请帮帮我。

您可以定义一个自定义排序顺序数组,将code的每个可能值按所需顺序排列。

$custom_sort_order = array(
    'shipping' => 1,
    'coupon' => 2,
    'sub_total' => 3,
    'tax' => 4,
    'total' => 5);

那么您可以在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;
});