php – 如何过滤关联数组?

前端之家收集整理的这篇文章主要介绍了php – 如何过滤关联数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须处理重构,以减少 PHP中的代码行数,以过滤关联数组.
所以我在MysqL中选择DB,以获得一个关联数组.所以我的“对象”有一个类别和一个姓氏字段.
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);
}

预先感谢您的帮助.

警长的方法是最简单的.只是为了它,这是一个 array_filter()方法(以防你必须有一个未经过滤的数组):
$array = [];
$categories = array("A","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","D");

$array = [
    ['category' => 'A','Surname' => 'A Name 1'],['category' => 'A','Surname' => 'A Name 2'],['category' => 'B','Surname' => 'B Name 1'],'Surname' => 'B Name 2'],'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
        (
        )

)
原文链接:https://www.f2er.com/php/136624.html

猜你在找的PHP相关文章