MaryCoding
MaryCoding

Reputation: 664

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',
        ],
    ],
];

Upvotes: 0

Views: 42

Answers (1)

B. Desai
B. Desai

Reputation: 16436

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

Upvotes: 4

Related Questions