在WooCommerce中,我具有“位置”的产品属性pa_location
,通过该属性可以对订单项进行排序。当订单商品的位置相同时,我想按SKU对其进行排序。因此,请先按位置排序,然后再按SKU排序。
我查看了“ PHP usort sorting multiple fields” ,但是我无法弄清楚它如何应用并且对我的功能有效。
我有这个自定义函数,可以按pa_location
进行排序,但是无法使其也按_sku
进行排序。
我尝试实现引用的帖子中有关排序的一些示例。
add_filter( 'woocommerce_order_get_items', function( $items, $order ) {
uasort( $items,
function( $a, $b ) {
return strnatcmp( $a['pa_location'], $b['pa_location'] );
}
);
return $items;
}, 10, 2 );
我希望使用此功能按位置排序,然后按SKU排序。现在,它仅按位置排序。
答案 0 :(得分:1)
根据“ PHP usort sorting multiple fields” 答案线程尝试以下操作:
add_filter( 'woocommerce_order_get_items', 'filter_order_get_items_callback', 10, 2 );
function filter_order_get_items_callback( $items, $order ) {
uasort( $items,
function( $a, $b ) {
if( $a['pa_location'] == $b['pa_location'] ) {
return strcmp( $a['_sku'], $b['_sku'] );
}
return strnatcmp( $a['pa_location'], $b['pa_location'] );
}
);
return $items;
}
测试:
$items = array (
0 => array ( 'pa_location' => 'Marseille',
'_sku' => '27458C' ),
1 => array ( 'pa_location' => 'Nice',
'_sku' => '32458A' ),
2 => array ('pa_location' => 'Cannes',
'_sku' => '35C7L5' ),
3 => array ('pa_location' => 'Marseille',
'_sku' => '387B85'),
4 => array ( 'pa_location' => 'Cannes',
'_sku' => '25A587' )
);
uasort( $items, function( $a, $b ) {
if( $a['pa_location'] == $b['pa_location'] ) {
return strcmp( $a['_sku'], $b['_sku'] );
}
return strnatcmp( $a['pa_location'], $b['pa_location'] );
} );
// Raw output
echo '<pre>'; print_r( $items ); echo '<pre>';
我们得到以下输出:
Array
(
[2] => Array
(
[pa_location] => Cannes
[_sku] => 25A587
)
[4] => Array
(
[pa_location] => Cannes
[_sku] => 35C7L5
)
[0] => Array
(
[pa_location] => Marseille
[_sku] => 27458C
)
[3] => Array
(
[pa_location] => Marseille
[_sku] => 387B85
)
[1] => Array
(
[pa_location] => Nice
[_sku] => 32458A
)
)
我们期望的是,先排在pa_location
之后,然后排在_sku
。
答案 1 :(得分:0)
尝试一下:
spanGaps
我已经为add_filter( 'woocommerce_order_get_items', function( $items, $order ) {
uasort( $items,
function( $a, $b ) {
return strnatcmp( $a['pa_location'], $b['pa_location'] );
}
);
uasort( $items,
function( $a, $b ) {
return strnatcmp( $a['_sku'], $b['_sku'] );
}
);
return $items;
}, 10, 2 );
重新运行了uasort()
。我尚未测试代码,但我希望它可以为您完成这项工作。