John Davidson

How can I find all results in a PHP array, merge values, and then merge into another array

0 comments
Message:


Using PHP, I have an array like this:


Array 1


[
{epid: "123", hash: "xxxxxx"},
{epid: "456", hash: "xxxxxx"},
{epid: "789", hash: "xxxxxx"},
{epid: "123", hash: "xxxxxx"},
{epid: "123", hash: "xxxxxx"},
]

Then, I have a second array like this:


Array 2


[
{epid: "123", name: "This is a title"},
{epid: "456", name: "This is a title"},
{epid: "789", name: "This is a title"}
]

My goal is to get all hash from array one and add them to the appropriate record in array 2. From this example, the results would be:


[
{epid: "123", name: "This is a title", hash: [ xxxxxx, xxxxxx, xxxxxx ] },
{epid: "456", name: "This is a title", hash: [ xxxxxx ] },
{epid: "789", name: "This is a title", hash: [ xxxxxx ] }
]

I'm sure there are multiple loops here, but for the life of me, I can't wrap my brain around it.



My Answer:
1, name: "John", age: 25},
{epid: 2, name: "Jane", age: 30},
{epid: 3, name: "Alice", age: 28}
]

_Array 2_
[
{epid: 1, result: "Pass"},
{epid: 2, result: "Fail"},
{epid: 3, result: "Pass"}
]

I want to merge these two arrays based on the "epid" key and get the following result:

_Final Array_
[
{epid: 1, name: "John", age: 25, result: "Pass"},
{epid: 2, name: "Jane", age: 30, result: "Fail"},
{epid: 3, name: "Alice", age: 28, result: "Pass"}
]

Here's how you can achieve this in PHP:

php
$array1 = [
['epid' => 1, 'name' => 'John', 'age' => 25],
['epid' => 2, 'name' => 'Jane', 'age' => 30],
['epid' => 3, 'name' => 'Alice', 'age' => 28]
];

$array2 = [
['epid' => 1, 'result' => 'Pass'],
['epid' => 2, 'result' => 'Fail'],
['epid' => 3, 'result' => 'Pass']
];

$finalArray = [];

foreach ($array1 as $item1) {
foreach ($array2 as $item2) {
if ($item1['epid'] == $item2['epid']) {
$finalArray[] = array_merge($item1, $item2);
}
}
}

print_r($finalArray);


This code snippet will merge the two arrays based on the "epid" key and create the final array as shown above.

Rate this post

3 of 5 based on 7257 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us