In PHP compare two arrays then make a new array based on a specific structure?

你。 提交于 2019-12-11 19:18:04

问题


I want to make this array:

(-,-,2,4,-,1,-,-,5)

using array $ar1 and $ar2:

$report[0]['progress'] = '2';
$report[1]['progress'] = '4';
$report[2]['progress'] = '1';
$report[3]['progress'] = '5';
$progress0 = $report[0]['progress'];
$progress1 = $report[1]['progress'];
$progress2 = $report[2]['progress'];
$progress3 = $report[3]['progress'];

$report[0]['month'] = 'Nov';
$report[1]['month'] = 'Dec';
$report[2]['month'] = 'Feb';
$report[3]['month'] = 'May';
$month0 = $report[0]['month'];
$month1 = $report[1]['month'];
$month2 = $report[2]['month'];
$month3 = $report[3]['month'];

$ar1 = array($progress0,$progress1,$progress2,$progress3);
$ar2 = array($month0,$month1,$month2,$month3);

The final array would follow the format (sep,oct,nov,dec,jan,feb,mar,apr,may) So if a month is present in $ar2 it would show the corresponding number in $ar1. If the month is not present it would show a -.

Hence the goal of (-,-,2,4,-,1,-,-,5)

How can this be done?

UPDATED QUESTION

To simplify I'm trying to take:

$ar1 = array(2,4,1,5);
$ar2 = array('Nov','Dec','Feb','May');

and using this array to set the structure:

$ar3 = array('Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May')

In a new array replace the months from $ar2 with numbers from the same locations in $ar1, so $ar2[2] would become $ar1[2], Months that are not present in $ar2 would be given a -.

So the new array would become

('-','-',2,4,'-',1,'-','-',5)

回答1:


This should get you started in the right direction

$ar3 = array('Nov'=>'-', 'Sept'=>'-', ...);
for($i = 0; $i < count($ar1); $i++){
    $ar3[$ar2[$i]] = $ar1[$i]; 
}


来源:https://stackoverflow.com/questions/21662611/in-php-compare-two-arrays-then-make-a-new-array-based-on-a-specific-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!