• 8
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Merging two multidimensional arrays on specific key

Let's say I have following arrays:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science

        [4] => Array
            (
                [id] => 1
                [name] => Sports
            )
    )

And the second one:

Array
    (
        [0] => Array
            (
                [id] => 1
                [title] => Sport
            )

        [1] => Array
            (
                [id] => 7
                [title] => Sci
            )

        [3] => Array
            (
                [id] => 4
                [title] => Comp

        [4] => Array
            (
                [id] => 5
                [title] => Edu
            )
    )

And desired output is:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
                [title] => Edu
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
                [title] => Comp
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science
                [title] => Sci

        [4] => Array
            (
                [id] => 1
                [name] => Sports
                [title] => Sport
            )
    )

I have managed to merge these arrays with simply:

foreach($first as $key => $value){
    $result[$key] = array_merge($first[$key], $second[$key]);
}

But the output is not combined correctly:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
                [title] => Sport
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
                [title] => Sci
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science
                [title] => Comp

        [4] => Array
            (
                [id] => 1
                [name] => Sports
                [title] => Edu
            )
    )

The problem is I would like to merge these arrays on the same id. Desired output sorting should be same as in the first array.

How can I achieve this? Any help is much appreciated.

You can just do a nested loop and check if the id values match, then add title to $first (or name to $second)

foreach($first as $key => $value){
    foreach($second as $value2){
        if($value['id'] === $value2['id']){
            $first[$key]['title'] = $value2['title'];
        }               
    }
}
  • 10
Reply Report

You code works fine. Your expectations are simply incorrect. For example in one array 4th element id holds 1 but in another array, 4th element id is 5, so your "merge these arrays on the same id" makes no sense as by merging 4th elements into one you also merge their children, and since id is used in both arrays, once value HAVE TO be gone as there cannot be two equal keys in array.

EDIT

you have to merge manually as PHP functions merge based on keys while you want to merge based on content:

$result = array();
foreach( $arrayA as $keyA => $valA ) {
  foreach( $arrayB as $keyB => $valB ) {
     if( $valA['id'] == $valB['id'] ) {
       $result[$keyA] = $valA + $valB;

       // or if you do not care output keys, just
       // $result[] = $valA + $valB;
     }
  }
}
  • 2
Reply Report
      • 2
    • I have corrected some mistakes in outputs, sorry for that. What I want is to take e.g $first[0]['id'] (equals 5) find same id in the second array, here $second[4]['id'] and merge them into new array like so: array('id'=>5, 'name'=>'Education', 'title'=>'Edu'). Isn't that possible?

To provide an alternative approach available in PHP 5.5+.

Since the ordering of the two arrays is not identical, first use array_column to index the arrays by the id.

This will allow you to use array_replace_recusrive on the id indexed arrays.

array_replace_recursive will merge the values in the arrays matching the index association of both array sets.

Optionally use array_values to reindex the array, removing the id index association.

Example https://3v4l.org/ndv2j

$first = array_column($first, null, 'id');
$second = array_column($second, null, 'id');
$result = array_values(array_replace_recursive($first, $second));

Result

Array
(
    [0] => Array
        (
            [id] => 5
            [name] => Education
            [title] => Edu
        )

    [1] => Array
        (
            [id] => 4
            [name] => Computers
            [title] => Comp
        )

    [2] => Array
        (
            [id] => 7
            [name] => Science
            [title] => Sci
        )

    [3] => Array
        (
            [id] => 1
            [name] => Sports
            [title] => Sport
        )

)
  • 2
Reply Report

As long as both arrays always have every id in them, what about sorting the two arrays by that 'id' field, then letting php do the merge?

function cmp($a, $b) {
  return ((int) $a['id'] < (int) $b['id']) ? -1 : 1;
}

usort($array1, 'cmp');
usort($array2, 'cmp');

$result = array_merge($array1, $array2);

Have not tested the code, but it demonstrates the idea.

  • 1
Reply Report

Do not use foreach in foreach,that might be too slow when the array so big.

$idArray = array_column($secondArray,'title','id');
foreach($firstArray as $key => $val){
  $firstArray[$key]['title'] = (isset($idArray[$val['id']])) ? $idArray[$val['id']] : 'some title';
}
  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions