3

Is it possible to group rows based on a value within the subarray?

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 
    )
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Homer_J
  • 3,277
  • 12
  • 45
  • 65

3 Answers3

3

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);
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
2

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;
    });
}
hindmost
  • 7,125
  • 3
  • 27
  • 39
1

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.

Chris Lam
  • 3,526
  • 13
  • 10