根据特定值对数组进行分组

时间:2017-07-27 04:18:42

标签: php

我有一个基本数组,我希望根据x字段值对其进行分组。我想将值保持在一个数组中。我已经尝试了多种方法,对于循环,但没有运气得到它我想要的方式。如何达到以下预期效果?

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

1 个答案:

答案 0 :(得分:4)

希望这是你想要的:

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