简体   繁体   中英

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

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM