根据列值对数据行进行分组

2022-03-09 00:00:00 arrays grouping php

是否可以根据子数组中的值对行进行分组?

数组

Array (
[4f5hfgb] => Array (
[0] => ACME
[1] => 4f5hfgb
[2] => Aberdeen
)
[sdf4ws] => Array (
[0] => ACME
[1] => sdf4ws
[2] => Birmingham 
)
[dfgdfg54] => Array (
[0] => EDNON
[1] => dfgdfg54
[2] => Birmingham 
)
[345bfg] => Array (
[0] => EDNON
[1] => 345bfg
[2] => Birmingham 
)
[345fgfd] => Array (
[0] => VALVE
[1] => 345fgfd
[2] => Birmingham 
)
)

是否可以对[0]中具有相同值的那些进行分块?

所需输出

Array (
    [4f5hfgb] => Array (
    [0] => ACME
    [1] => 4f5hfgb
    [2] => Aberdeen
    )
    [sdf4ws] => Array (
    [0] => ACME
    [1] => sdf4ws
    [2] => Birmingham 
    )
)

Array (
    [dfgdfg54] => Array (
    [0] => EDNON
    [1] => dfgdfg54
    [2] => Birmingham 
    )
    [345bfg] => Array (
    [0] => EDNON
    [1] => 345bfg
    [2] => Birmingham 
    )
)

Array (
    [345fgfd] => Array (
    [0] => VALVE
    [1] => 345fgfd
    [2] => Birmingham 
    )
)

解决方案

如果我理解您的问题,您正在尝试将键值0相同的所有元素分组到同一数组中。您不能使用array_chunk执行此操作,但是下面的循环会生成分组的数组

$result = array();

foreach($arr as $k => $v) {
    $result[$v[0]][$k] = $v;
}

print_r($result);

相关文章