0

Having the following two different arrays in php:

Array1
(
    [0] => Array
        (
            [id] => 1
            [name] => William
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

    [2] => Array
        (
            [id] => 3
            [name] => Michael
        )

)
Array2
(
    [0] => Array
        (
            [id] => 11128
            [name] => John
        )

    [1] => Array
        (
            [id] => 11127
            [name] => Adam
        )

    [2] => Array
        (
            [id] => 11126
            [name] => Andrew
        )

    [3] => Array
        (
            [id] => 11125
            [name] => William
        )

    [4] => Array
        (
            [id] => 11124
            [name] => Bob
        )

)

Can I somehow find matching names so the output will be like:

Array1 (1, id:2) matches Array2 (4, id:11124) with name: Bob
Array1 (0, id:1) matches Array2 (3, id:11125) with name: William

sorry if it's unclear

2 Answers 2

2

You can always try a simple foreach loop:

<?php
foreach($array1 as $key1=>$value1) {
    foreach($array2 as $key2=>$value2) {
        if($value1['name'] === $value2['name']) {
            sprintf('Array1 (%d, id:%d) matches Array2 (%d, id:%d) with name: %s', $key1, $value1['id'], $key2, $value2['id'], $value1['name']);
        }
    }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1
foreach($array1 as $i=>$x){
  foreach($array2 as $k=>$y){
    if($x['name'] == $y['name']){
      echo "Array1 ($i, id:{$x['id']}) matches Array2 ($k, id:{$y['id']}) with name: {$x['name']}\n";
      break;
    }
  }
}

4 Comments

+1 for us having identical code except for the sprintf vs echo!
@PhpMyCoder: And I have a break after the echo :-P
well true, and an empty result array. I think you could have outdone me if you stored the matches in it and then mapped them to vsprintf.
@PhpMyCoder: Oops. I was gonna use the $result array, but then I didn't.

Your Answer

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