我有两个数组:
Array
(
[0] => Array
(
[Date] => 2019-05-04 18:40:00
[Item] => Prasanta Kumar Ray
[Code] =>
[Amount] => 150
)
[1] => Array
(
[Date] => 2019-05-04 21:23:00
[Item] => Dr Praveenkumar
[Code] =>
[Amount] => 150
)
)
第二
Array
(
[0] => Array
(
[Date] => 2019-05-04 18:45:00
[Item] => TC DC ESR
[Code] =>
[Amount] => 60
)
)
如何将它们连接在一起以获得长度为3的关联数组?提前谢谢。
我尝试了array_merge和array_push。没用。
答案 0 :(得分:2)
您可以使用array_merge
将它们合并为一个array
$arr1 = Array
(
'0' => Array
(
'Date' => '2019-05-04 18:40:00',
'Item' => 'Prasanta Kumar Ray',
'Code' => '',
'Amount' => 150
),
'1' => Array
(
'Date' => '2019-05-04 21:23:00',
'Item' => 'Dr Praveenkumar',
'Code' => '',
'Amount' => 150
)
);
$arr2 = Array
(
'0' => Array
(
'Date' => '2019-05-04 18:45:00',
'Item' => 'TC DC ESR',
'Code' => '',
'Amount' => 60
)
);
$res = array_merge($arr1,$arr2);
输出
Array
(
[0] => Array
(
[Date] => 2019-05-04 18:40:00
[Item] => Prasanta Kumar Ray
[Code] =>
[Amount] => 150
)
[1] => Array
(
[Date] => 2019-05-04 21:23:00
[Item] => Dr Praveenkumar
[Code] =>
[Amount] => 150
)
[2] => Array
(
[Date] => 2019-05-04 18:45:00
[Item] => TC DC ESR
[Code] =>
[Amount] => 60
)
)
答案 1 :(得分:1)
确定吗?
我尝试了 array_merge 和array_push。没用。
尝试使用array_merge()
或array_merge_recursive()
。两者都应该为您工作。
<?php
$array1 = array
(
array
(
"Date" => "2019-05-04 18:40:00",
"Item" => "Prasanta Kumar Ray",
"Code" => null,
"Amount" => 150
)
,
array
(
"Date" => "2019-05-04 21:23:00",
"Item" => "Dr Praveenkumar",
"Code" =>null ,
"Amount" => 150
)
);
$array2 = array
(
array
(
"Date" => "2019-05-04 18:45:00",
"Item" => "TC DC ESR",
"Code" => null,
"Amount" => 60
)
);
$array3 = array_merge_recursive($array1,$array2);
print_r($array3);
?>
答案 2 :(得分:1)
如果要合并并保持数组按日期排序,则需要使用array_column使数组与日期关联,对数组进行ksort并用array_values重置键。
$new = array_merge(array_column($arr1, null, 'Date'), array_column($arr2, null, 'Date'));
ksort($new);
$new = array_values($new);
var_dump($new);
此输出:
array(3) {
[0]=>
array(4) {
["Date"]=>
string(19) "2019-05-04 18:40:00"
["Item"]=>
string(18) "Prasanta Kumar Ray"
["Code"]=>
string(0) ""
["Amount"]=>
int(150)
}
[1]=>
array(4) {
["Date"]=>
string(19) "2019-05-04 18:45:00"
["Item"]=>
string(9) "TC DC ESR"
["Code"]=>
string(0) ""
["Amount"]=>
int(60)
}
[2]=>
array(4) {
["Date"]=>
string(19) "2019-05-04 21:23:00"
["Item"]=>
string(15) "Dr Praveenkumar"
["Code"]=>
string(0) ""
["Amount"]=>
int(150)
}
}