我有一个数组需要按键合并,并使用该键的值创建一个新数组。我搜索和搜索没有结果。任何帮助都会很棒!
原始数组
Array
(
[0] => Array
(
[name] => Key 1
[value] => Value 1
)
[2] => Array
(
[name] => Key 1
[value] => Value 2
)
[3] => Array
(
[name] => Key 2
[value] => Value 1
)
[4] => Array
(
[name] => Key 1
[value] => Value 3
)
[5] => Array
(
[name] => Key 2
[value] => Value 2
)
)
最终数组应该如下所示
Array
(
[0] => Array
(
[name] => Key 1
[value] => Array
(
[0] => Value 1
[1] => Value 2
[2] => Value 3
)
)
[1] => Array
(
[name] => Key 2
[value] => Array
(
[0] => Value 1
[1] => Value 2
)
)
)
答案 0 :(得分:1)
<?php
$array = Array
(
0 => Array
(
'name' => 'Key 1',
'value' => 'Value 1'
),
2 => Array
(
'name' => 'Key 1',
'value' => 'Value 2'
),
3 => Array
(
'name' => 'Key 2',
'value' => 'Value 1'
),
4 => Array
(
'name' => 'Key 1',
'value' => 'Value 3'
),
5 => Array
(
'name' => 'Key 2',
'value' => 'Value 2'
)
);
$tmpArray = array();
foreach ($array as $smallArray) {
if(!is_array($tmpArray[$smallArray['name']]))
$tmpArray[$smallArray['name']] = array();
$tmpArray[$smallArray['name']][] = $smallArray['value'];
}
$finalArray = array();
foreach ($tmpArray as $key => $value) {
$someArray['name'] = $key;
$someArray['value'] = $value;
$finalArray[] = $someArray;
}
print_r($finalArray);
我为你写了解决方案,但下次你应该先尝试自己