In foreach, the number of circular query data is less, but the performance is relatively low, the better solution is to collect the ID, in a one-time query, but this caused the data structure is not we use PHP functions can be merged, today tested:
Functions written with the following bytes can be used to resolve
The data taken from the database is always more or less inconsistent with the data structure we have in mind, similar to the following two arrays, to form a SQL similar to the left join after the two array merges:
Copy Code code as follows:
$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 for You '
),
1 => Array (
' id ' => 9478138,
' Message ' => ' Miss '
)
);
If you want to associate these two arrays with a left join similar to SQL, what function do we use? Well, I wrote it myself without seeing him.
At first, it was nested loops: inefficient
Copy Code code as follows:
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 a two-time loop: Form a way like left join
Copy Code code as follows:
$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 for You '
),
1 => Array (
' id ' => 9478138,
' Message ' => ' Miss '
)
);
function _mergerarray ($array 1, $array 2, $field 1, $field 2 = ') {
$ret = Array ();
Method of using array subscript
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:
Copy Code code as follows:
Array
(
[0] => Array
(
[ID] => 9478137
[Message] =>
[Create_time] => 1394760724
)
[1] => Array
(
[ID] => 9478138
[Message] => miss
[Create_time] => 1394760725
)
[2] => Array
(
[ID] => 9478138
[Message] => miss
[Create_time] => 1394760725
)
)
The equivalent of a LEFT join, right?