简体   繁体   中英

PHP array_chunk - split based on variable

Is it possible to array_chunk based on a value within the array?

Array

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

Is it possible to chunk those with the same value in [0] ?

Desired output

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

If I understand your question, you're trying to group all elements that have the same value for key 0 into the same array. You can't do this with array_chunk but the loop below produces the grouped array

$result = array();

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

print_r($result);

Try this:

$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;
    });
}

No, array_chunk splits array to chunks based on size. You may consider looping through into the array and chunk it into your desired structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM