Saturday, January 29, 2022

[FIXED] How to merge multidimensional with specific value

Issue

I have a problem in merging two-dimensional arrays

I have three arrays with the same months

first array: (Jobseeker)

Array
(
    [0] => Array
        (
            [MONTH] => 5
            [jobseeker] => 4
        )

    [1] => Array
        (
            [MONTH] => 6
            [jobseeker] => 4
        )

)

second array: (company)

Array
(
    [0] => Array
        (
            [MONTH] => 6
            [company] => 11
        )

)

third array: (jobs)

Array
(
    [0] => Array
        (
            [MONTH] => 6
            [job] => 20
        )

)

I tried this code:

$total_stats = array_merge_recursive($jobseeker_stats, $company_stats, $job_stats);

I expect the output is:

Array
(
     [0] => Array
        (
            [MONTH] => 5
            [jobseeker] => 4
        )
     [1] => Array
        (
            [MONTH] => 6
            [jobseeker] => 4
            [company] => 11
            [job] => 20
        )

Solution

You need to use array_column(), array_search() with 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);

Output:-https://3v4l.org/BKJqj



Answered By - Anant Kumar Singh

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.