PHP array_chunk - 基于变量拆分

时间:2014-07-13 15:45:24

标签: php arrays

是否可以基于数组中的值来array_chunk

阵列

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

3 个答案:

答案 0 :(得分:3)

如果我理解了您的问题,那么您正尝试将具有相同值的所有元素0组合到同一个数组中。您无法使用array_chunk执行此操作,但下面的循环会生成分组数组

$result = array();

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

print_r($result);

答案 1 :(得分:2)

试试这个:

$values = array_unique(array_map(
    function ($v) { return $v[0]; },
    $array
));

$result = array();
foreach ($values as $val) {
    $result[] = array_filter($array, function ($v) use ($val) {
        return $v[0] == $val;
    });
}

答案 2 :(得分:1)

不,array_chunk根据大小将数组拆分为块。您可以考虑循环进入数组并将其组合成所需的结构。