合并二维数组时遇到问题
我有三个相同的月份数组
第一个数组:(求职者)
Array
(
[0] => Array
(
[MONTH] => 5
[jobseeker] => 4
)
[1] => Array
(
[MONTH] => 6
[jobseeker] => 4
)
)
第二个数组:(公司)
Array
(
[0] => Array
(
[MONTH] => 6
[company] => 11
)
)
第三组:(工作)
Array
(
[0] => Array
(
[MONTH] => 6
[job] => 20
)
)
我尝试了以下代码:
$total_stats = array_merge_recursive($jobseeker_stats, $company_stats, $job_stats);
我希望输出是:
Array
(
[0] => Array
(
[MONTH] => 5
[jobseeker] => 4
)
[1] => Array
(
[MONTH] => 6
[jobseeker] => 4
[company] => 11
[job] => 20
)
答案 0 :(得分:3)
您需要将array_column()和array_search()与foreach()一起使用
$seconArrayMonths = array_column($array2,'MONTH');
$thirdArrayMonths = array_column($array3,'MONTH');
foreach($array1 as &$arr){
$secondArrayMonthKey = array_search($arr['MONTH'],$seconArrayMonths);
if($secondArrayMonthKey !== false){
$arr['company'] = $array2[$secondArrayMonthKey]['company'];
}
$thirdArrayMonthKey = array_search($arr['MONTH'],$thirdArrayMonths);
if($thirdArrayMonthKey !== false){
$arr['job'] = $array3[$secondArrayMonthKey]['job'];
}
}
print_r($array1);
答案 1 :(得分:1)
$jobSeeker = array('0' => array('MONTH' => 5,'jobseeker' => 4),'1' => array('MONTH' => 6, 'jobseeker' => 4));
$company = array('0' => array('MONTH' => 6,'company' => 11));
$jobs = array('0' => array('MONTH' => 6,'job' => 20));
$mergeArray = array();
foreach($jobSeeker as $js){
$mergeArray[$js['MONTH']]['MONTH'] = $js['MONTH'];
$mergeArray[$js['MONTH']]['jobseeker'] = $js['jobseeker'];
}
foreach($company as $c){
$mergeArray[$c['MONTH']]['MONTH'] = $c['MONTH'];
$mergeArray[$c['MONTH']]['company'] = $c['company'];
}
foreach($jobs as $j){
$mergeArray[$j['MONTH']]['MONTH'] = $j['MONTH'];
$mergeArray[$j['MONTH']]['job'] = $j['job'];
}
$result = array();
foreach($mergeArray as $m){
array_push($result, $m);
}
print_r($result);
答案 2 :(得分:1)
您可以使数组具有关联性,并使用array_replace_recursive。
$jobSeeker = array_column($jobSeeker, Null, "MONTH");
$company = array_column($company, Null, "MONTH");
$jobs = array_column($jobs, Null, "MONTH");
$jobSeeker = array_replace_recursive($jobSeeker, $company, $jobs);
var_dump($jobSeeker);
输出
array(2) {
[5]=>
array(2) {
["MONTH"]=>
int(5)
["jobseeker"]=>
int(4)
}
[6]=>
array(4) {
["MONTH"]=>
int(6)
["jobseeker"]=>
int(4)
["company"]=>
int(11)
["job"]=>
int(20)
}
}