2016-02-26 151 views
0

我用下面WooCommerce:產品排序根據產品ID

$sortingArr = $my_cart; 
$data = array(); 
$result = array(); 

    if ($wc_query->have_posts()) : 
     while ($wc_query->have_posts()) : 
     $wc_query->the_post(); 
     $product = new WC_Product(get_the_ID()); 

    $product_permalink = get_permalink(); 
    $product_title = get_the_title(); 
    $product_thumbnail_id = get_post_thumbnail_id(); 
    $product_thumbnail_url = wp_get_attachment_image_src($product_thumbnail_id, 'medium', true); 
    $product_description = apply_filters('the_content',get_the_excerpt()); 
    $product_price = $product->get_price_html(); 
    $product_cart = $product->single_add_to_cart_text(); 
    $product_id = $product->id; 

    $data[$product->id] = array(
          $product_permalink, 
          $product_title, 
          $product_thumbnail_url[0], 
          $product_description, 
          $product_price, 
          $product_cart, 
          $product_id); 

     endwhile; 
     wp_reset_postdata(); 

    //sorting 
    foreach($sortingArr as $val){ 
    $result[array_search($val, $data)] = $val; 
    } 

    foreach ($result as $value) { 
      <!-- displaying HTML output --> 
    } 
    endif; 

代碼現在我想這些產品的產品ID這是目前使用usort()的車排序拉動所有可用的產品WooCommerce或asort()描述的功能和方法here。當我將刪除排序代碼並顯示$data數組時,所有工作都正常。

編輯: $data數組具有與產品ID相關的密鑰,這可以幫助根據購物車內部的產品ID排序另一個產品ID。

任何提示什麼,我做錯了什麼?

+0

您可以包括你使用的是帶有ASORT或usort未使用的代碼? –

+0

@TomášNavara更新OP與分選部分 – JackTheKnife

回答

0

得到它解決

首先,我已分配鍵將$data產品陣列

$data[$product->id] = array(
         "permalink" => $product_permalink, 
         "title" => $product_title, 
         "thumbnail_url" => $product_thumbnail_url[0], 
         "description" => $product_description, 
         "price" => $product_price, 
         "in_cart" => $product_cart, 
         "id" => $product_id); 

正如我已經分配product_id的鍵$data陣列我能夠用下面

$sortedProducts = []; 

foreach ($sortingArr as $id) { 
    $sortedProducts[] = $data[$id]; 
} 

一個循環,如果有人沒有$data陣列與相關的密鑰進行排序,但你必須它們存儲在陣列內,你可以隨時使用array_column重新索引您的陣列

// array_column is only available in PHP 5.5+ 
$data = array_column($data, null, 'id'); 

,然後排序使用滿足如上所述。

-1

您有$product->id鍵陣列的$data陣列。因此,您不能搜索$ data數組,因爲您的針本身必須是陣列(更確切地說是指向同一陣列)

考慮到您的代碼在位置6(第7個元素)上分配了產品ID,您可以將

//sorting 
foreach($sortingArr as $val){ 
    $result[array_search($val, $data)] = $val; 
} 

// sorting 
foreach($sortingArr as $val){ 
    // $data is an array of arrays, so you must look through item in position $data[$i][6], where product ID is located in your case 
    foreach($data as $product_id => $d){ 
     // if present here 
     if(array_search($val, $d[6]) !== false){ 
      $result[$product_id] = $d; 

      // we have a match, no need to loop more 
      break; 
     } 
    } 
} 
+0

這是不正確回答我的問題,因爲我期待通過鑰匙從低到高 – JackTheKnife

+0

不只是排序按另一個數組的數組我發現的bug在你的代碼 –

+0

確定如果該代碼的工作原理應如此?在使用具有預定義5個ID的'$ sortingArray'排序僅5個產品後,我得到一個空的'$ result'數組 – JackTheKnife