MaryCoding MaryCoding - 3 years ago 85
PHP Question

Grouping array based on an specific value

I have a basic array where I would like to group it based on the

x
field value. I would like to keep the values still in one array. I have tried multiple things foreach, for loops but no luck to get it how I would like. How can I achieve the below desired result?

$originalArray = [
[
'x' => 'test',
'y' => 'blah',
],
[
'x' => 'test',
'y' => 'blah',
],
[
'x' => 'test2',
'y' => 'blah',
],
[
'x' => 'test2',
'y' => 'blah',
],
];

Desired Result:
[
'test' => [
[
'x' => 'test',
'y' => 'blah',
],
[
'x' => 'test',
'y' => 'blah',
],
],
'test2' => [
[
'x' => 'test2',
'y' => 'blah',
],
[
'x' => 'test2',
'y' => 'blah',
],
],
];

Answer Source

Hope this is what you want :

$originalArray = [
    [
        'x' => 'test',
        'y' => 'blah',
    ],
    [
        'x' => 'test',
        'y' => 'blah',
    ],
    [
        'x' => 'test2',
        'y' => 'blah',
    ],
    [
        'x' => 'test2',
        'y' => 'blah',
    ],
];
$desired_array = array();
foreach ($originalArray as $key => $value) {
  $desired_array[$value['x']][]=$value;
}
var_dump($desired_array);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download