我有以下关联数组列表:
([0] => ([name]=> "Paul", [year] => 2010, items => 4),
[1] => ([name]=> "Paul", [year] => 2011, items => 5),
[2] => ([name]=> "George", [year] => 2010, items => 13),
[3] => ([name]=> "George", [year] => 2011, items => 10))
我需要获取由键“名称”的唯一值列出的关联数组的列表。 我的输出应该是:
( ([name] => "Paul") => ([0] => ([year] => 2010, items => 4),
[1] => ([year] => 2011, items => 5)),
([name] => "George") => (([0] => ([year] => 2010, items => 13),
[1] => ([year] => 2011, items => 10)))
我该怎么办?
答案 0 :(得分:1)
您可以简单地遍历数组并以所需的格式创建一个新数组
$data = [
['name' => "Paul", 'year' => 2010, 'items' => 4],
['name' => "Paul", 'year' => 2011, 'items' => 5],
['name' => "George", 'year' => 2010, 'items' => 13],
['name' => "George", 'year' => 2011, 'items' => 10]
];
$newArr = [];
foreach($data as $occ){
$newArr[$occ['name']][] = [ 'year' => $occ['year'],
'items' => $occ['items']
];
}
结果:
Array
(
[Paul] => Array
(
[0] => Array
(
[year] => 2010
[items] => 4
)
[1] => Array
(
[year] => 2011
[items] => 5
)
)
[George] => Array
(
[0] => Array
(
[year] => 2010
[items] => 13
)
[1] => Array
(
[year] => 2011
[items] => 10
)
)
)
答案 1 :(得分:0)
您可以这样做
foreach($data as $d){
$newArr[$d['name']][] = array('year'=>$d['year'],'items'=>$d['items']);
}
答案 2 :(得分:0)
请尝试使用此功能以列出键“名称”的唯一值
例如:
function array_group(array $data, $by_column) {
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
if (isset($result[$column])) {
$result[$column][] = $item;
} else {
$result[$column] = array($item);
}
}
return $result;
}
$result = array_group($assocArray,'name');