2012-10-05 47 views
0

我有兩個陣列這樣通過陣列排序爲找到匹配

Array 
(
    [0] => MYU_MP1 
    [1] => 4cc00e5f580f00c2e54193fde7129608 
    [2] => da8bbfdb40be0dc2b3312ca1037f994a 
    [3] => d4cfaa8db24c4b81db506189360b6b99 
) 
Array 
(
    [0] => MYU_SC1 
    [1] => MYU_SC2 
    [2] => MYU_SF1 
    [3] => MYU_SC3 
    [4] => MYU_AD1 
    [5] => MYU_AD2 
    [6] => MYU_AD3 
    [7] => MYU_AD4 
    [8] => MYU_RC1 
    [9] => MYU_RC2 
    [10] => MYU_RC3 
    [11] => MYU_RC4 
    [12] => MYU_RC5 
    [13] => MYU_RC6 
    [14] => MYU_RC7 
    [15] => MYU_RC8 
) 

第一個別名爲「交付」,而另一個「non_deliverable」 和第三陣列

Array 
(
    [d8df18561040f3d9bd9868f5c5aaa7c2] => Array 
     (
      [rowid] => d8df18561040f3d9bd9868f5c5aaa7c2 
      [id] => MYU_SC1 
      [qty] => 1 
      [price] => 500 
      [name] => WAEC Scratch Card 
      [service_image] => assets/img/waec.jpg 
      [service_category] => scratch_cards 
      [subtotal] => 500 
     ) 

的第三陣列的別名 「cart_items」

[f68964856a61092d9a2566d024a0ba28] => Array 
     (
      [rowid] => f68964856a61092d9a2566d024a0ba28 
      [id] => MYU_MP1 
      [qty] => 1 
      [price] => 210000 
      [name] => Apple iPhone 5 16gb 
      [service_image] => 
      [service_category] => mobile-phones 
      [subtotal] => 210000 
     ) 

我已經寫穿過第三陣列應該循環,以確定是否所述第三數組的一個「id」元素是第一或第二陣列

//sort through cart items 
    foreach ($cart_items as $key => $item) { 
     if(in_array($item['id'], $deliverables) && in_array($item['id'], $non_deliverables)) { 
      $deliverable = TRUE; 
      $non_deliverable = TRUE; 
     } 

     if(in_array($item['id'], $deliverables) && !in_array($item['id'], $non_deliverables)) { 
      $deliverable = TRUE; 
     } 

     if(in_array($item['id'], $non_deliverables) && !in_array($item['id'], $deliverables)) { 
      $non_deliverable = TRUE; 
     } 

     if($deliverable && $non_deliverable) 
      $type = "both"; 
     if($non_deliverable) 
      $type = "non-deliverable"; 
     if($deliverable) 
      $type = "deliverable"; 
    } 
    return $type; 

的成員但一種功能,當第三陣列具有匹配在第一個和第二個數組中,該函數返回「交付物」。我不正確的做法是什麼?

+0

嘗試從我的答案中將例子的第一部分縮短。 –

回答

1

您的排序順序錯誤。 $可交付和$ non_deliverable的檢查應該是最後一個。或者,您可以使用if-else-if-else結構。

+0

謝謝你做到了 – MrFoh

2
function somefunction() 
     foreach ($cart_items as $key => $item) { 
      $deliverable = in_array($item['id'], $deliverables); 
      $non_deliverable = in_array($item['id'], $non_deliverables); 

      $type = "none"; 
      if ($deliverable && $non_deliverable) { 
       $type = "both"; 
      } elseif ($deliverable && !$non_deliverable) { 
       $type = "deliverable"; 
      } elseif (!$deliverable && $non_deliverable) { 
       $type = "non-deliverable"; 
      } 
     } 
     return $type; 
}