【问题标题】:How to swap array elements in php?如何在php中交换数组元素?
【发布时间】:2016-04-18 15:37:30
【问题描述】:

我有一个数组

           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] => coupon 到 [code] => sub_total 时交换数组索引,如果有优惠券可用。 我希望优惠券的位置高于小计。 我希望 sub_total 的位置高于大桶。 这怎么可能? 请帮帮我。

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。

标签: php arrays swap


【解决方案1】:

您可以定义一个自定义排序顺序数组,将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;
});

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2019-05-27
    • 2010-10-26
    相关资源
    最近更新 更多