2015-04-30 90 views
8

我必須處理重構,以減少PHP中代碼的行數,以過濾關聯數組。 因此,我正在從MySQL中的數據庫中進行選擇,以獲得關聯數組。所以我的「對象」有一個類別和一個姓氏字段。如何篩選關聯數組?

while ($row = mysqli_fetch_array($result)) { 
     $array[] = $row['category']; 
     $array[] = $row['Surname']; 
    } 

我想從這個數組中獲取其他許多子數組,按類別分割。我的意思是該類別陣列識別可能是:

$categories = array("A","B","C","D"); 

所以我想要的東西,是獲得每個類別一個數組,其中包含所有姓這一類的。 因此,假設該方法的工作原理,類似的東西:

$arrayFiltered = method_filter($array_asso,"A"); 

最後我想這樣的事情:

foreach ($categories as &$value) { 
     $arrayFiltered = method_filter($array_asso,$value); 
     my_method_which_needs_the_filtered_array($arrayFiltered); 
} 

預先感謝您的幫助。

+0

你需要在適當的DB標準化的表結構!你有這種方法(以逗號分隔的數據存儲數據)會給你很多頭痛 –

+0

DB有一個表,它是:Category,Surname as field。現在工作,我正在爲每個類別做一個查詢,但這會增加一些延遲,代碼可能會改進。 –

+0

,這是:什麼? –

回答

1

警長的方法是最簡單的。只是爲了它的緣故,這裏是array_filter()(以防萬一,你必須有一個未經過濾的陣列以及)的方法:

$array = []; 
$categories = array("A","B","C","D"); 

while ($row = mysqli_fetch_array($result)) { 
    $item = [ 
     'category' => $row['category'], 
     'surname' => $row['Surname'] 
    ]; 

    $array[] = $item; 
} 

$categorized = []; 

foreach ($categories as $category) { 
    $categorized[$category] = array_filter($array, function($item) use ($category) { 
     return $item['category'] == $category; 
    }); 
} 

這裏是概念,而不需要一個數據庫連接的證明:

$categories = array("A","B","C","D"); 

$array = [ 
    ['category' => 'A', 'Surname' => 'A Name 1'], 
    ['category' => 'A', 'Surname' => 'A Name 2'], 
    ['category' => 'B', 'Surname' => 'B Name 1'], 
    ['category' => 'B', 'Surname' => 'B Name 2'], 
    ['category' => 'B', 'Surname' => 'B Name 3'], 
    ['category' => 'C', 'Surname' => 'C Name'], 
]; 

$categorized = []; 

foreach ($categories as $category) { 
    $categorized[$category] = array_filter($array, function($item) use ($category) { 
     return $item['category'] == $category; 
    }); 
} 

print_r($categorized); 

輸出:

Array 
(
    [A] => Array 
     (
      [0] => Array 
       (
        [category] => A 
        [Surname] => A Name 1 
       ) 

      [1] => Array 
       (
        [category] => A 
        [Surname] => A Name 2 
       ) 

     ) 

    [B] => Array 
     (
      [2] => Array 
       (
        [category] => B 
        [Surname] => B Name 1 
       ) 

      [3] => Array 
       (
        [category] => B 
        [Surname] => B Name 2 
       ) 

      [4] => Array 
       (
        [category] => B 
        [Surname] => B Name 3 
       ) 

     ) 

    [C] => Array 
     (
      [5] => Array 
       (
        [category] => C 
        [Surname] => C Name 
       ) 

     ) 

    [D] => Array 
     (
     ) 

) 
3

就我而言 - 你需要一個數組,它將包含所有的surnamecategory明智的,以便您可以輕鬆訪問它們。這應該有助於 -

while ($row = mysqli_fetch_array($result)) { 
    $categories[$row['category']][] = $row['Surname']; 
} 

只是存儲類別爲key和所有surname作爲值到key

+0

因此,代碼的最後部分應該是:foreach($ categories as&$ value){ my_method_which_needs_the_filtered_array($ categories [$ value]); }不是嗎?如果'$ categories [$ value]'包含類別,則爲 –

+0

。 :) –