I have to deal with a refactoring, to reduce the number of lines of code in PHP, to filter an associative array. So I'm making a select from DB in MySQL, to get an associative array. So my "Object" has a category and a surname field.
while ($row = mysqli_fetch_array($result)) {
$array[] = $row['category'];
$array[] = $row['Surname'];
}
I want to obtain from this array, as many other sub-array, splitted by the category. I mean the category Array identification may be:
$categories = array("A","B","C","D");
So what I want, is to obtain one Array for each Category, which contains all the Surname, of that category. So suppose that the method works, something like that:
$arrayFiltered = method_filter($array_asso,"A");
At the end I want something like that:
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.
As far as i get you - you need one array which will contain all the surname
category
wise so that you can access them easily. This should help -
while ($row = mysqli_fetch_array($result)) {
$categories[$row['category']][] = $row['Surname'];
}
Simply store the category as key
and all the surname
as values to that key
.
Sergeant's approach is the easiest. Just for the sake of it, here is an approach with array_filter()
(just in case you have to have an unfiltered array as well):
$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 the need of a database connection:
$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
(
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With