php 按子数组值对数组分组

vhipe2zx  于 2023-01-24  发布在  PHP
关注(0)|答案(6)|浏览(207)

我有一个子数组的数组,格式如下:

array
(
    a => array ( id = 20, name = chimpanzee )
    b => array ( id = 40, name = meeting )
    c => array ( id = 20, name = dynasty )
    d => array ( id = 50, name = chocolate )
    e => array ( id = 10, name = bananas )
    f => array ( id = 50, name = fantasy )
    g => array ( id = 50, name = football )
)

我想根据每个子数组中的id字段将其分组到一个新数组中。

array
(
    10 => array
          (
            e => array ( id = 10, name = bananas )
          )
    20 => array
          (
            a => array ( id = 20, name = chimpanzee )
            c => array ( id = 20, name = dynasty )
          )
    40 => array
          (
            b => array ( id = 40, name = meeting )
          )
    50 => array
          (
            d => array ( id = 50, name = chocolate )
            f => array ( id = 50, name = fantasy )
            g => array ( id = 50, name = football )
          )
)
p4rjhz4m

p4rjhz4m1#

$arr = array();

foreach ($old_arr as $key => $item) {
   $arr[$item['id']][$key] = $item;
}

ksort($arr, SORT_NUMERIC);
ioekq8ef

ioekq8ef2#

foreach($array as $key => $value){
   $newarray[$value['id']][$key] = $value;
}

var_dump($newarray);

小菜一碟)

uelo1irk

uelo1irk3#

下面的代码改编了@Tim库珀的代码,以减少内部数组之一不包含id时的Undefined index: id错误:

$arr = array();

foreach($old_arr as $key => $item)
{
    if(array_key_exists('id', $item))
        $arr[$item['id']][$key] = $item;
}

ksort($arr, SORT_NUMERIC);

但是,它将删除没有id的内部数组。
例如

$old_arr = array(
    'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
    'b' => array ( 'id' => 40, 'name' => 'meeting' ),
    'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
    'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
    'e' => array ( 'id' => 10, 'name' => 'bananas' ),
    'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
    'g' => array ( 'id' => 50, 'name' => 'football' ),
    'h' => array ( 'name' => 'bob' )
);

将完全删除'h'数组。

bqujaahr

bqujaahr4#

您也可以使用ouzo-goodies中的Arrays::groupBy():

$groupBy = Arrays::groupBy($array, Functions::extract()->id);

print_r($groupBy);

结果:

Array
(
    [20] => Array
        (
            [0] => Array
                (
                    [id] => 20
                    [name] => chimpanzee
                )

            [1] => Array
                (
                    [id] => 20
                    [name] => dynasty
                )

        )

    [40] => Array
        (
            [0] => Array
                (
                    [id] => 40
                    [name] => meeting
                )

        )

    [50] => Array
        (
            [0] => Array
                (
                    [id] => 50
                    [name] => chocolate
                )

            [1] => Array
                (
                    [id] => 50
                    [name] => fantasy
                )

            [2] => Array
                (
                    [id] => 50
                    [name] => football
                )

        )

    [10] => Array
        (
            [0] => Array
                (
                    [id] => 10
                    [name] => bananas
                )

        )

)

这里是ArraysFunctions的文档。

ej83mcc0

ej83mcc05#

下面是一个函数,它将一个数组作为第一个参数,将一个条件(字符串或回调函数)作为第二个参数。该函数返回一个新数组,并根据请求对数组进行分组。

/**
 * Group items from an array together by some criteria or value.
 *
 * @param  $arr array The array to group items from
 * @param  $criteria string|callable The key to group by or a function the returns a key to group by.
 * @return array
 *
 */
function groupBy($arr, $criteria): array
{
    return array_reduce($arr, function($accumulator, $item) use ($criteria) {
        $key = (is_callable($criteria)) ? $criteria($item) : $item[$criteria];
        if (!array_key_exists($key, $accumulator)) {
            $accumulator[$key] = [];
        }

        array_push($accumulator[$key], $item);
        return $accumulator;
    }, []);
}

下面是给定的数组:

$arr = array(
    'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
    'b' => array ( 'id' => 40, 'name' => 'meeting' ),
    'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
    'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
    'e' => array ( 'id' => 10, 'name' => 'bananas' ),
    'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
    'g' => array ( 'id' => 50, 'name' => 'football' )
);

以及将函数与字符串和回调函数一起使用的示例:

$q = groupBy($arr, 'id');
print_r($q);

$r = groupBy($arr, function($item) {
    return $item['id'];
});
print_r($r);

两个示例中的结果相同:

Array
(
    [20] => Array
        (
            [0] => Array
                (
                    [id] => 20
                    [name] => chimpanzee
                )

            [1] => Array
                (
                    [id] => 20
                    [name] => dynasty
                )

        )

    [40] => Array
        (
            [0] => Array
                (
                    [id] => 40
                    [name] => meeting
                )

        )

    [50] => Array
        (
            [0] => Array
                (
                    [id] => 50
                    [name] => chocolate
                )

            [1] => Array
                (
                    [id] => 50
                    [name] => fantasy
                )

            [2] => Array
                (
                    [id] => 50
                    [name] => football
                )

        )

    [10] => Array
        (
            [0] => Array
                (
                    [id] => 10
                    [name] => bananas
                )

        )

)

在上面的示例中,传递回调函数有些多余,但是当您传入对象数组、多维数组或您想要根据其进行分组的任意对象时,使用回调函数会有用武之地。

nue99wik

nue99wik6#

也许值得一提的是你也可以使用php array_reduce函数

$items = [
    ['id' => 20, 'name' => 'chimpanzee'],
    ['id' => 40, 'name' => 'meeting'],
    ['id' => 20, 'name' => 'dynasty'],
    ['id' => 50, 'name' => 'chocolate'],
    ['id' => 10, 'name' => 'bananas'],
    ['id' => 50, 'name' => 'fantasy'],
    ['id' => 50, 'name' => 'football'],
];

// Grouping
$groupedItems = array_reduce($items, function ($carry, $item) {
    $carry[$item['id']][] = $item;
    return $carry;
}, []);
// Sorting
ksort($groupedItems, SORT_NUMERIC);

print_r($groupedItems);

https://www.php.net/manual/en/function.array-reduce.php

相关问题