通过值对数组进行分组

时间:2019-05-20 09:45:35

标签: php arrays multidimensional-array

我有一个像这样的数组

数组    (

[1] => Array
    (
        [name] => 123
        [id] => 105740727
        [email] =>fghfhfh
        [phrases_relevant] => 123
        [searches_id] => 105740727
    )

[2] => Array
    (
        [name] => porshe
        [id] => 105713889
        [email] => fghfghf
        [phrases_relevant] => porshe
        [searches_id] => 105713889
    )

 [3] => Array
    (
        [name] => porshe
        [id] => 105713889
        [email] => fghfghf
        [phrases_relevant] => merce
        [searches_id] => 105713889
    )

我需要通过值将该组分组。输出数组应如下所示。第二和第三维度具有相同的searchs_id

  [0] => Array
    (
        [email] => fghfghf
        [projects]=>
              [porshe] => [porshe, merce]
  [1] => ...

编辑;

我尝试过

    foreach ($results as $key => $result) {
         $testArray[]['projects'][$result['name']][] = $result['phrases_relevant'];

但这会插入一个短语;

2 个答案:

答案 0 :(得分:3)

您需要先按searches_id进行排序,然后应用循环,

function sortByOrder($a, $b)
{
    return $a['searches_id'] - $b['searches_id'];
}
usort($myArray, 'sortByOrder');
foreach ($myArray as $key => $value) {
    $result[$value['searches_id']]['email']      = $value['email'];
    $result[$value['searches_id']]['projects'][] = $value['phrases_relevant'];
}
$result = array_values($result); // reset keys used for array generation

工作demo

答案 1 :(得分:1)

您可以使用foreach

$res = [];
foreach($arr as $key => $value){

array_key_exists($value['id'], $res) ?
    ($res[$value['id']]['phrases_relevant'] = $res[$value['id']]['phrases_relevant'].','.$value['phrases_relevant'])
:
($res[$value['id']] = ['email' => $value['email'],'phrases_relevant' => $value['phrases_relevant']]);
}
print_r(array_values($res))

Live Demo