9

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.

2
  • You need proper normalized table structure in DB !! This approach you have(store data in comma separated values per record) will give you lot of headache Commented Apr 30, 2015 at 10:35
  • The DB has a table, which is: Category, Surname as field. Right now works, that I'm making for each category, a query, but this add some delay and the code could be improve. Commented Apr 30, 2015 at 10:39

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, the last part of the code, should be: foreach ($categories as &$value) { my_method_which_needs_the_filtered_array($categories[$value]); } isn't it ?
if $categories[$value] contains the category. :)
2

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
        (
        )

)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.