PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 29, 2022

[FIXED] How to merge multidimensional with specific value

 January 29, 2022     codeigniter, mysql, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing