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

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@serakfalcon in this case i prefer foreach
yeah after a couple minutes thinking about it I see why.
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;
    });
}

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.