时间:2021-07-01 10:21:17 帮助过:3人阅读
$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'
)
);
如果要将这两个数组,类似于sql中的left join 关联起来我们用什么函数呢?额我没有找见就自己写了
刚开始的时候,用的是嵌套循环:效率低下
代码如下:
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;
}
改进后的办法,使用数组下标,使用两次循环:形成类似于left join的方式
代码如下:
$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();
//使用数组下标的办法
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;
打印出来结果如下:
代码如下:
Array
(
[0] => Array
(
[id] => 9478137
[message] => love you
[create_time] => 1394760724
)
[1] => Array
(
[id] => 9478138
[message] => miss you
[create_time] => 1394760725
)
[2] => Array
(
[id] => 9478138
[message] => miss you
[create_time] => 1394760725
)
)
相当于left join了吧?http://www.bkjia.com/PHPjc/743150.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/743150.htmlTechArticle在foreach中循环查询数据代码量比较少,但是性能比较低,好点的解决办法是将id收集起来,用in一次性查询,但是这引发了数据结构不是我们...