0

How can I find the match of the key of an array in another array?

For instance,

array 1,

Array
(
    [0] => Array
        (
            [parent_id] => 4 // the lookup key
            [count] => 7
        )

    [1] => Array
        (
            [parent_id] => 5 // the lookup key
            [count] => 2
        )

)

array 2,

Array
(
    [0] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )

    [1] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 4 // the match 
        )

    [2] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )

    [3] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 5 // the match 
        )

    [4] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )
)

result that I am after,

Array
(
    [0] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 4
            [count] => 7
        )

    [1] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 5
            [count] => 2
        )

)
2
  • 1
    Turn array 1 into an associative array where the parent ID is the key. Then loop through array 2 adding the corresponding count to each element. Commented Nov 29, 2014 at 15:21
  • thanks. I can imagine how this part can be done - Turn array 1 into an associative array where the parent ID is the key. but not sure about the second part - ...adding the corresponding count to each element. can you show an example please? Commented Nov 29, 2014 at 15:26

1 Answer 1

1

Try this ..

The array_column function will return the parent_id from the second array, the array_search function will match the two parent_ids from array1 and array2, and the array_merge function will merge the two arrays with the matching parent_ids.

Untested, so excuse any small syntax errors.

$array1 = array(); // this is your first array in your example
$array2 = array(); // this is your second array in your example
$result = array(); // this is what you're looking for

foreach ($array1 as $row) {
  $result[] = array_merge($row, $array2[array_search($row["parent_id"], array_column($array2,"parent_id")];
}
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.