phparraysmultidimensional-arrayarray-combine

Combine Two Multidimensional Arrays on matching key values in PHP


Problem

i have two multidimensional arrays that look like this,

1st Array

array(
      [0] => Array
        (
        [course_id] => 10
        [topic] => Booda-hood, advice and an important pit.
        [lesson_id] => 10
    )

[1] => Array
    (
        [course_id] => 10
        [topic] => new topic
        [lesson_id] => 11
    )

)

2nd array

  Array
    (
    [0] => Array
      (
        [id] => 10
        [description] => Lorem Ipsum is blablabla
        [course_title] => Lorem Ipsum is 
    )

[1] => Array
    (
        [id] => 11
        [description] => Lorem Ipsum is simply dummy text of 
        [course_title] => Lorem Ipsum 
    )

)

I want to combine both arrays like this if($1st[0]['lesson_id'] == $2nd[0]['id'])

3rd array

      array(
          [0] => Array
          (
           [course_id] => 10
           [topic] => Booda-hood, advice and an important pit.
           [lesson_id] => 10
           [id] => 10
           [description] => Lorem Ipsum is blablabla
           [course_title] => Lorem Ipsum is 
       )

[1] => Array
    (
        [course_id] => 10
        [topic] => new topic
        [lesson_id] => 11
        [id] => 11
        [description] => Lorem Ipsum is simply dummy text of 
        [course_title] => Lorem Ipsum
    )

)

I hope I explain everything!


Solution

  • <?php
    // Your array
    $arr1 = [
      [
      'course_id' => 10,
      'topic' => 'Booda-hood, advice and an important pit.',
      'lesson_id' => 10
      ],
      [
      'course_id' => 10,
      'topic' => 'Booda-hood, advice and an important pit.',
      'lesson_id' => 11
      ]
    ];
    
    $arr2 = [
      [
      'id' => 10,
      'description' => '10 Lorem Ipsum is blablabla',
      'course_title' => '10 Lorem Ipsum is blablabla'
      ],
      [
      'id' => 11,
      'description' => '11 Lorem Ipsum is blablabla',
      'course_title' => '11 Lorem Ipsum is blablabla'
      ]
    ];
     
    // Combining arrays implementation 
    
    foreach ( $arr2 as $k=>$v )
    {
      // rename array2 `id` to `lesson_id`
      $arr2[$k]['lesson_id'] = $arr2[$k] ['id'];
      unset($arr2[$k]['id']);
    }
    
    // array_replace_recursive — Replaces elements from passed arrays into the first array recursively   
    print_r(array_replace_recursive($arr1, $arr2));
    ?>
    

    OUTPUT

    [
      {
        "course_id": 10,
        "topic": "Booda-hood, advice and an important pit.",
        "lesson_id": 10,
        "description": "10 Lorem Ipsum is blablabla",
        "course_title": "10 Lorem Ipsum is blablabla"
      },
      {
        "course_id": 10,
        "topic": "Booda-hood, advice and an important pit.",
        "lesson_id": 11,
        "description": "11 Lorem Ipsum is blablabla",
        "course_title": "11 Lorem Ipsum is blablabla"
      }
    ]
    

    Hope this helps!

    Ref - array_replace_recursive