PHP combines two associative array functions---improve function efficiency
In foreach, the number of circular query data code is relatively small, but the performance is relatively low, the better solution is to collect the ID, use in a one-time query, but this raises the data structure is not our own function with PHP can be combined, today tested a bit:
Functions written using the following byte can be resolved
Data extracted from the database is always more or less in line with our data structure, similar to the following two arrays, to form SQL similar to the left join after the two array merge:
PHP combines two associative array functions---improve the efficiency of the function $test1 = Array (
0 = Array (
' id ' = 9478137,
' Create_time ' = 1394760724
),
1 = Array (
' id ' = 9478138,
' Create_time ' = 1394760725
),
2 = Array (
' id ' = 9478138,
' Create_time ' = 1394760725
)
);
$test 2 = Array (
0 = Array (
' id ' = 9478137,
' Message ' = ' Love You '
),
1 = Array (
' id ' = 9478138,
' Message ' = ' Miss You '
)
);
what function would we use if we were to associate the two arrays, similar to the left join in SQL? Well, I wrote it myself without seeing him.
At first, a nested loop is used: inefficient
function _mergerarray ($array 1, $array 2, $field 1, $field 2 = ") {
$ret = Array ();
foreach ($array 1 as $key 1 = $value 1) {
foreach ($array 2 as $key 2 = $value 2) {
if ($value 1[$field 1] = = $value 2[$field 2]) {
$ret [$key 1] = Array_merge ($value 1, $value 2);
}
}
}
return $ret;
}
The improved approach, using array subscripts, uses two loops: a way to form a similar left join
$test 1 = Array (
0 = Array (
' id ' = 9478137,
' Create_time ' = 1394760724
),
1 = Array (
' id ' = 9478138,
' Create_time ' = 1394760725
),
2 = Array (
' id ' = 9478138,
' Create_time ' = 1394760725
)
);
$test 2 = Array (
0 = Array (
' id ' = 9478137,
' Message ' = ' Love You '
),
1 = Array (
' id ' = 9478138,
' Message ' = ' Miss You '
)
);
function _mergerarray ($array 1, $array 2, $field 1, $field 2 = ") {
$ret = Array ();
Ways to use array subscripts
foreach ($array 2 as $key = = $value) {
$array 3[$value [$field 1]] = $value;
}
foreach ($array 1 as $key = = $value) {
$ret [] = Array_merge ($array 3[$value [$field 1]], $value);
}
return $ret;
}
$ret = _mergerarray ($test 1, $test 2, ' id ', ' id ');
Print_r ($ret); exit;
Print out the results as follows:
Array
(
[0] = = Array
(
[id] = 9478137
[Message]
[Create_time] = 1394760724
)
[1] = = Array
(
[id] = 9478138
[Message] = Miss You
[Create_time] = 1394760725
)
[2] = = Array
(
[id] = 9478138
[Message] = Miss You
[Create_time] = 1394760725
)
)
Is it equivalent to a LEFT join?