2017-09-11 82 views
0

我創建了下面這個數組的數組元素,包含所有產品及其所有類別:foreach循環多維數組,但只循環通過與特定的鍵

$result = $wpdb->get_results("SELECT product_nr, category FROM erp_product_categories",ARRAY_A); 
$product_categories = array(); 
    foreach($result as $row){ 
    $product_categories[$row["product_nr"]][] = $row["category"]; 
    } 

(product_nr是一個整數和類別是一個字符串)

然後我想檢查,如果一個產品的類別之一與其他變量相匹配,並且如果多數民衆贊成的情況下返回true:

foreach($product_categories[$ean] as $product_categorie) { 
    $manages_post = in_array($product_categorie, $this->term_link_conditions); 

    if($manages_post == true){ 
     break; 
    } 
} 
return $manages_post; 

但我正在錯誤提供的foreach

無效的參數()

是它不可能循環只能通過與特定鍵的陣列的元素?

編輯: 數組看起來像這樣

Array 
(
    [10001] => Array  //product_nr 
    (
     [0] => 1   //category 
     [1] => 4   //category 
    ) 

    [10002] => Array 
    (
     [0] => 1 
     [1] => 20 
    ) 
    //... 
) 
+0

是什麼'$ product_categories'和'$ ean'的價值? –

+0

這意味着該數組爲空或不存在。 – Akintunde007

+0

'$ product_categorie'實際上是一個類別數組?你的命名很混亂。它也不包含安全網。例如,如果產品沒有類別,它不會出現在數組中,即使我期望產品ID在那裏,但內容是類別的空數組。最後但並非最不重要的,是否考慮過查詢'$ ean'的類別,而不是全部獲取,然後在PHP代碼中進行篩選? – GolezTrol

回答

0

你應該檢查什麼要傳遞到的foreach是如果你不知道它的將是使用is_array功能

數組數組可以隨時查詢使用下面的PHP代碼示例:

if (is_array($product_categories[$ean])) { 
 

 
    foreach ($product_categories[$ean] as $product_categorie) { 
 
    //do something 
 
    } 
 
}

檢查出所有的foreach語句,並查看as之前的事情,以確保它實際上是一個數組。使用var_dump轉儲它。

0

試試這個:

if(is_array($product_categories) && sizeof($product_categories) > 0) { 
    foreach($product_categories as $key => $product_categorie) { 
     if($manages_post = in_array($key, $this->term_link_conditions)){ 
      return $manages_post; 
     } 
    } 
} 
+0

我不想檢查in_array中的密鑰,我想檢查具有特定鍵的值(product_nr(= ean))例如,如果密鑰是10002,那麼我希望檢查以下值:[10002] =>數組 ( [0] => 1 [1] => 2 [2] => 8 //檢查類別1,2和8 ) – Kvasha

0

我想出了一個辦法做到這一點

$product_category = $product_categories[$ean]; 

      if (is_array($product_category)) { 
       $matches = array_intersect($product_category, $this->term_link_conditions); 
       if(sizeof($matches) > 0){ 
        $manages_post = true; 
       } 
      }