我有一个像这样的数组
数组 (
[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
)
我需要通过值对这个组进行分组。输出数组应如下所示。 第二个维度和第三个维度具有相同的 search_id
[0] => Array
(
[email] => fghfghf
[projects]=>
[porshe] => [porshe, merce]
[1] => ...
编辑;
我尝试过;
foreach ($results as $key => $result) {
$testArray[]['projects'][$result['name']][] = $result['phrases_relevant'];
但这会插入一个短语;
您需要先按
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
工作演示。
您可以使用
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))
通过在无体循环中使用对称数组解构语法,您可以仅隔离所需的行值并将数据推送到组中。 循环完成后,调用
array_values()
重新索引结果数组。 演示
foreach (
$array as [
'id' => $id,
'name' => $name,
'email' => $result[$id]['email'],
'phrases_relevant' => $result[$id]['projects'][$name][]
]
);
var_export(array_values($result));
输出:
array (
0 =>
array (
'email' => 'fghfhfh',
'projects' =>
array (
123 =>
array (
0 => 123,
),
),
),
1 =>
array (
'email' => 'fghfghf',
'projects' =>
array (
'porshe' =>
array (
0 => 'porshe',
1 => 'merce',
),
),
),
)