foreach结果的订单号

时间:2014-02-05 13:10:33

标签: php wordpress

我有一个函数,我收集数据然后爆炸,这个函数在一段时间内,wordpress

global $woocommerce; 
global $wpdb;
$args = array( 'post_type' => 'product', 'stock' => 1, 'posts_per_page' => -1);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();         
$order_id = $loop->post->ID;
foreach($product as $sku){
    $sku = $product->get_sku();
    $sku_s = explode('-', $sku);
    $camp = $sku_s[0];
    $itm_n = $sku_s[1];
}

<h6><span class="a1"><?php echo $camp;?></span>-<span class="a2"><?php echo $itm_n;?></span></h6>

我的输出
就像这样

<h6><span class="a1">581</span>-<span class="a2">20</span></h6>
<h6><span class="a1">581</span>-<span class="a2">50</span></h6>
<h6><span class="a1">581</span>-<span class="a2">1</span></h6>
<h6><span class="a1">581</span>-<span class="a2">6</span></h6>
<h6><span class="a1">581</span>-<span class="a2">9</span></h6>

581-20
581-1
581-9 ....等...... ..

但是我需要对oder的数字进行排序,例如

581-1
581-6
581-9 ....等等......

谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

为你的skus创建一个比较函数,即

function myComparison(a,b) {
    a.id<b.id;
}

然后在标准数组排序中使用它

$skus.sort(myComparison);

无法确切地看到你的物品是如何布局的,但我希望这有助于引导你找到正确的答案。

答案 1 :(得分:0)

首先,这个foreach循环没有多大意义。为什么要迭代$sku以立即用$product->get_sku()覆盖它?

//what you wrote
foreach($product as $sku){
    $sku = $product->get_sku();
    $sku_s = explode('-', $sku);
    $camp = $sku_s[0];
    $itm_n = $sku_s[1];
}

//did you mean this?
foreach($products as $product){
    $sku = $product->get_sku();
    $sku_s = explode('-', $sku);
    $camp = $sku_s[0];
    $itm_n = $sku_s[1];
}

假设您可以识别每次迭代中提取的变量(并且它类似于上面的更正循环),您可以尝试以下两种方法之一。

(1)您是否尝试将orderby传递给您正在运行的WP_Queryhttp://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

(2)您需要重新索引结果,以便您的订单基于SKU的自然排序顺序。

while ( $loop->have_posts() ) : $loop->the_post();
    $order_id = $loop->post->ID;

    //create a new array to hold by SKU
    $sortProducts = array();

    foreach($products as $product){
        $sortProducts[$product->get_sku()] = $product;
    }

endwhile;

//sort natural order
ksort($sortProducts, SORT_NATURAL);

//notice that this is a different foreach loop here
foreach($sortProducts as $sku => $product){
    $sku = $product->get_sku();
    $sku_s = explode('-', $sku);
    $camp = $sku_s[0];
    $itm_n = $sku_s[1];
    echo "<h6><span class=\"a1\">$camp</span>-<span class=\"a2\">$itm_n</span></h6>";
}

示例输出图像

CLICK