How to filter an associative array?

I need to deal with refactoring to reduce the number of lines of code in PHP in order to filter an associative array. Therefore, I make a choice from DB to MySQL to get an associative array. Thus, my “Object” has a category and last name field.

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

I want to get from this array, like many other sub-matrices, separated by category. I mean the identification of the Array category:

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

So what I want is to get one array for each category that contains the entire surname of this category. Suppose the method works, something like this:

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

In the end, I want something like this:

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

Thank you in advance for your help.

+8
arrays php associative-array
source share
2 answers

The sergeant approach is the simplest. Just for the sake of this, here is the approach with array_filter() (just in case, you should have an unfiltered array):

 $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; }); } 

Here is a proof of concept without having to connect to a database:

 $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); 

Output:

 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 ( ) ) 
+1
source share

As far as I understand - you need one array that will contain all the surname category so that you can easily access them. This should help -

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

Just save the category as key and all surname as values ​​up to key .

+3
source share

All Articles