2014-10-18 65 views
0

因此,我有這個簡單的代碼來獲取每個產品,查找類型,並將該類別顯示在我的網站中。現在防止數組中的多個條目

public function get_categories() 
{ 
    $products = $this->get_products(); 

    $categories = array(); 

    $i = '-1'; 

    foreach($products as $product) 
    { 
     $name = ucfirst(strtolower($this->ci->inflect->pluralize($product['type']))); 

     if(!in_array($name, $categories)) 
     { 
      $i++; 

      $categories[$i] = array(
       'name' => $name, 
       'type' => strtolower($product['type']), 
      ); 
     } 
    } 

    return $categories; 
} 

,直到我需要通過typename所以現在我正在做一個多維數組以及它工作得很好。

現在顯然name從來沒有在數組categories,因爲它內部的另一個數組中。

如何檢測數組categories內的數組中是否已經存在name

+1

你爲什麼不使用'$ name'爲數組的鍵而不是一些數字?會給你一個一維數組,你總是知道'$ categories [$ name]'是否設置 – kero 2014-10-18 21:00:06

+0

哇,我一直在這個顯然太長時間工作......謝謝。 – user3968645 2014-10-18 21:01:10

回答

0

您可以嘗試thiss 變化[$i]

$category[$name] 

$i++; 

if(!in_array($name, $categories[$i])) 
     { 


      $categories[$i] = array(
       'name' => $name, 
       'type' => strtolower($product['type']), 
      ); 
     } 
0
$categories[$i] = array(
       'name' => $name, 
       'type' => strtolower($product['type']), 
      ); 

變化到

$categories[$name] = array(
       'name' => $name, 
       'type' => strtolower($product['type']), 
      ); 

並添加

foreach($categories as $key=>$val){ 
$out[$i] = $categories[$key]; 
} 

或array_unique 或類似(陳述下面的鏈接)

http://php.net/manual/en/ref.array.php

但我不知道如果我理解正確的道路