1

I have array1 like this:

Array
(
[0] => Array
    (
        [0] => test
        [1] => 123
    )

[1] => Array
    (
        [0] => testx
        [1] => 456
    )

)

and array2 like this:

Array
(
[0] => Array
    (
        [0] => test
        [1] => somenumber
    )

[1] => Array
    (
        [0] => title
        [1] => sometitle
    )
[2] => Array
    (
        [0] => testx
        [1] => othernumber
    )

 )

I need output like this:

Array
(
[0] => Array
    (
        [0] => test
        [1] => 123
        [2] => somenumber
    )

[1] => Array
    (
        [0] => testx
        [1] => 456
        [1] => othernumber
    )

)

So I need to compare only value with [0]key of each array. I have tried combinations with array_intersect and array_diff but I just can't get it to work. Can anybody please point me in some direction, what is proper function/way to do this?

1 Answer 1

1

You can do it with some instructions :)

<?php

$array1[] = ['test',  '123'];
$array1[] = ['testx', '456'];

$array2[] = ['test', 'a'];
$array2[] = ['testx', 'b'];
$array2[] = ['other', 'c'];

$indexColumns = array_column($array1, 0);
// We extact an array of key/values for column 0
// = [0 => test, 1 => testx]

foreach( $array2 as $key => $value ) {
  // If we can find the value of the first column on the indexColumn
  if( ($foundKey = array_search($value[0], $indexColumns)) !== false ) {
    unset($value[0]);
    $array1[$foundKey] = array_merge($array1[$foundKey], $value);
  }
}

Output:

array (size=2)
  0 => 
    array (size=3)
      0 => string 'test' (length=4)
      1 => string '123' (length=3)
      2 => string 'a' (length=1)
  1 => 
    array (size=3)
      0 => string 'testx' (length=5)
      1 => string '456' (length=3)
      2 => string 'b' (length=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.