I have problem when try to merge two arrays in PHP.
I'm using laravel, so my queries look like:
$users = DB::table('users')
->select('name', 'user_id')
->get();
and
$speech = DB::table('users')
->select('user_id', DB::raw('AVG(point) as count'))
->leftJoin('evalute', 'users.user_id', '=', 'evalute.user_id')
->where('id_evaluate' ,'=', $id_evaluate)
->get();
For example:
$array1 = Array
(
[0] => stdClass Object
(
[user_id] => 1
[count] => 6.5
)
)
and array two follow:
$array2 = Array
(
[0] => stdClass Object
(
[name] => abc
[user_id] => 1
),
[1] => stdClass Object
(
[name] => xyz
[user_id] => 2
),
)
I want to merge two array above follow:
$array3 = Array
(
[0] => stdClass Object
(
[name] => abc
[user_id] => 1
[count] => 6.5
),
[1] => stdClass Object
(
[name] => xyz
[user_id] => 2
[count] => 0 //set default = 0 if not exist count
),
)
What can I do?
If this data is coming from a database then chances are the easiest way to achieve the result is using a join on your database query.
However - here's how you can do it with PHP:
Firstly you want to remap $array1
to user the user ID as its key. This way you avoid needing to nest a loop inside a loop to find the count, and can reference it immediately via the user ID which exists in both arrays:
// Re-map keys for array 1 so you don't have to loop it every time
$temp = array();
foreach ($array1 as $key => $values) {
$temp[$values->user_id] = $values;
}
$array1 = $temp
Here's an example of what $array1
looks like after you've done this.
Next, construct your $array3
based on $array2
with the added count
from $array1
if it exists, otherwise assign zero by default:
// Construct your output array
$array3 = array();
foreach ($array2 as $values) {
$values->count = array_key_exists($values->user_id, $array1)
? $array1[$values->user_id]->count
: 0;
$array3[] = $values;
}
Your output from $array3
will then look like this.