Monday, 27 August 2018

PHP: Update a multidimensional array based on values ​​of another multidimensional array

I have 2 different multidimensional array that are structured in the following way

ARRAY 1
    Array
    (
        [0] => Array
    (
        [0] => john
        [1] => AUTHOR
        [2] => PUBLISHER
    )
    [0] => Array
    (
        [0] => Smith
        [1] => AUTHOR
        [2] => PUBLISHER
    )
    )

ARRAY 2
 Array
 (
    [0] => Array
    (
        [0] => John
        [1] => www.john.com
        [2] => D
    )

        [1] => Array
    (
        [0] => Smith
        [1] => smith.com
        [2] => D
    )
    )

I would like two check if the value "john" from Array1 is available in array2. If it's the case, i retrieve the value of "www.john.com" in array2 and insert it in array 1
This is what i would like to achieve
FINAL ARRAY
ARRAY 1
    Array
    (
        [0] => Array
    (
        [0] => john
        [1] => www.john.com
        [2] => AUTHOR
        [3] => PUBLISHER
    )
    [0] => Array
    (
        [0] => Paul
        [1] => AUTHOR
        [2] => PUBLISHER
    )
    )

The array is dynamic, i put static values just to show what i would like to acheive.
Any help on this will be appreciated

This will work for you, but see comment below:
$arrayFirst = array(
     arraey('John', 'AUTHOR', 'PUBLISHER',),
     array('Smith', 'AUTHOR', 'PUBLISHER')) ;

$arraySecond = array(
     array('John', 'www.john.com', 'D'),
     array('Smith', 'smith.com', 'D'));

foreach ($arrayFirst as  $kye => $subArrayFirst){

  foreach ($arraySecond as $subArraySecond){
   if(in_array($subArrayFirst[0], $subArraySecond)) {
               $arrayFirst[$kye][] =  $subArraySecond[1];
          }
    }
}

var_dump($arrayFirst);

But in this case it is important the position of authow name and address

0 comments:

Post a Comment