3 回答
TA贡献1830条经验 获得超3个赞
array_merge使用 等的替代方法array_combine...只是两个简单的 foreach 循环并将值设置到一个新数组 ( $new_arr) 中。
$new_arr = [];
foreach($arr as $inner_arr) {
foreach($inner_arr as $key=>$value) {
$new_arr[$key] = $value;
}
}
更新 我不清楚 OP 想要什么,但我希望现在更清楚了:
试试这个:( 基本上将值添加到array[name of ZipName][{current key for the inner array}]
$arr = [
[
'ZipName' => 'data.zip',
'Age' => '45'
],
[
'ZipName' => 'data.zip',
'Name' => 'John'
],
[
'ZipName' => 'data2.zip',
'Age' => '27'
],
[
'ZipName' => 'data1.zip',
'Name' => 'Abram'
],
[
'ZipName' => 'data1.zip'
],
[
'ZipName' => 'data2.zip',
'City' => 'London'
],
[
'ZipName' => 'data2.zip',
'Name' => 'Inna'
],
[
'ZipName' => 'data1.zip',
'City' => 'London'
]
];
$new_arr = [];
foreach($arr as $key => $inner_arr) {
foreach($inner_arr as $ik => $item) {
$new_arr[$inner_arr['ZipName']][$ik] = $item;
}
}
输出:
Array
(
[data.zip] => Array
(
[ZipName] => data.zip
[Age] => 45
[Name] => John
)
[data2.zip] => Array
(
[ZipName] => data2.zip
[Age] => 27
[City] => London
[Name] => Inna
)
[data1.zip] => Array
(
[ZipName] => data1.zip
[Name] => Abram
[City] => London
)
)
做的时候:
$new_arr = array_values($new_arr);
关键只是做一个数字索引(如果重要的话)
Array
(
[0] => Array
(
[ZipName] => data.zip
[Age] => 45
[Name] => John
)
[1] => Array
(
[ZipName] => data2.zip
[Age] => 27
[City] => London
[Name] => Inna
)
[2] => Array
(
[ZipName] => data1.zip
[Name] => Abram
[City] => London
)
)
TA贡献1725条经验 获得超7个赞
您需要的是按索引处的唯一值进行分组['ZipName']
,然后分别合并这些组。这可以通过.array_reduce
例子:
<?php
declare(strict_types=1);
$input = [
[
'ZipName' => 'data_1.zip',
'Age' => 45,
], [
'ZipName' => 'data_1.zip',
'Name' => 'John',
], [
'ZipName' => 'data_1.zip',
], [
'ZipName' => 'data_1.zip',
'City' => 'Leicester',
],
[
'ZipName' => 'data_2.zip',
'Age' => 45,
], [
'ZipName' => 'data_2.zip',
'Name' => 'John',
], [
'ZipName' => 'data_2.zip',
], [
'ZipName' => 'data_2.zip',
'City' => 'Leicester',
],
];
$output = array_values(array_reduce($input, static function (array $acc, array $item): array {
$acc[$item['ZipName']] = array_merge($acc[$item['ZipName']] ?? [], $item);
return $acc;
}, []));
print_r($output);
TA贡献2036条经验 获得超8个赞
我想你要组合不同的数组,所以请使用数组合并。
$array0 = Array
(
"ZipName" => data.zip,
"Age" => 45
);
$array1 = Array
(
"ZipName" => data.zip,
"Name" => John
);
$array2 = Array
(
"ZipName" => data.zip
);
$array3 = Array
(
"ZipName" => data.zip,
"City" => Leicester
);
print_r(array_merge($array0, $array1, $array2, $array3));
输出:
Array ( [ZipName] => datazip
[Age] => 45
[Name] => John
[City] => Leicester )
- 3 回答
- 0 关注
- 120 浏览
添加回答
举报