The amount of code for looping data query in foreach is relatively small, but the performance is relatively low. A better solution is to collect the IDs and use in to query them all at once, but this leads to the fact that the data structure cannot be merged using PHP's own functions. , I tested it today:
The function written using the following bytes can solve the problem
The data taken out from the database is always more or less inconsistent with the data structure in our minds. Similar to the two arrays below, to form a merge of the two arrays similar to left join in SQL:
Copy code The code is as follows:
$test1 = Array(
0 => Array(
'id' => 9478137,
'create_time' => 1394760724
),
1 => ; Array(
'id' => 9478138,
'create_time' => 1394760725
),
2 => Array(
'id' => 9478138,
'create_time' => 1394760725
)
);
$test2 = array(
0 => array(
'id' => 9478137,
' message' => 'love you'
),
1 => array(
'id' => 9478138,
'message' => 'miss you'
)
);
If we want to associate these two arrays, similar to the left join in SQL, what function should we use? Well, I wrote it myself without looking for it
When I first started, I used nested loops: inefficient
Copy the code The code is as follows:
function _mergerArray($array1, $array2, $field1, $field2 = '') {
$ret = array();
foreach($array1 as $key1 => $value1 ) {
foreach ($array2 as $key2 => $value2) {
if($value1[$field1] == $value2[$field2]) {
$ret[$key1 ] = array_merge($value1, $value2);
}
}
}
return $ret;
}
Improved method, use array Subscript, use two loops: form a method similar to left join
Copy code The code is as follows:
$test1 = Array(
0 => Array(
'id' => 9478137,
'create_time' => 1394760724
),
1 => Array(
' id' => 9478138,
'create_time' => 1394760725
),
2 => Array(
'id' => 9478138,
'create_time' => ; 1394760725
)
);
$test2 = array(
0 => array(
'id' => 9478137,
'message' => 'love you'
),
1 => array(
'id' => 9478138,
'message' => 'miss you'
)
);
function _mergerArray($array1, $array2, $field1, $field2 = '') {
$ret = array();
//Use array subscript
foreach ($array2 as $key => $value) {
$array3[$value[$field1]] = $value;
}
foreach ($array1 as $key => $value ) {
$ret[] = array_merge($array3[$value[$field1]], $value);
}
return $ret;
}
$ret = _mergerArray( $test1, $test2, 'id', 'id');
print_r($ret);exit;
The printed result is as follows:
Copy code The code is as follows:
Array
(
[0] => Array
(
[id] => 9478137
[message] => love you
[create_time] => 1394760724
)
[1] =>
[message] => miss you
[create_time] => 🎜>[message] => miss you
[create_time] => 1394760725
)
)
Is it equivalent to left join?
http://www.bkjia.com/PHPjc/743150.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/743150.htmlTechArticleThe amount of code for looping data query in foreach is relatively small, but the performance is relatively low. A better solution is to change the id Collect it and query it in one time, but this triggers a data structure that is not ours...