在PHP中比较两个数组然后根据特定结构创建一个新数组?

时间:2022-10-23 12:18:20

I want to make this array:

我想制作这个数组:

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

using array $ar1 and $ar2:

使用数组$ ar1和$ 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 -.

最后一个数组将遵循格式(sep,oct,nov,dec,jan,feb,mar,apr,may)因此,如果$ ar2中存在一个月,它将在$ ar1中显示相应的数字。如果月份不存在,则会显示 - 。

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

因此( - , - ,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 -.

在一个新数组中,将$ ar2中的月份替换为$ ar1中相同位置的数字,因此$ ar2 [2]将变为$ ar1 [2],$ ar2中不存在的月份将被赋予 - 。

So the new array would become

所以新阵列将成为

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

1 个解决方案

#1


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]; 
}

#1


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]; 
}