Home > php教程 > php手册 > PHP将两个关联数组合并函数提高函数效率

PHP将两个关联数组合并函数提高函数效率

WBOY
Release: 2016-06-06 20:23:52
Original
1009 people have browsed it

在foreach中循环查询数据代码量比较少,但是性能比较低,使用下面的字节写的函数可以解决

在foreach中循环查询数据代码量比较少,但是性能比较低,好点的解决办法是将id收集起来,用in一次性查询,但是这引发了数据结构不是我们用PHP自带的函数可以合并的,今天测试了一下:

使用下面的字节写的函数可以解决

从数据库中取出来的数据总是或多或少不符合我们心目中的数据结构,类似于下面的俩个数组,要形成SQL中类似于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'
)
);


如果要将这两个数组,类似于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了吧?
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template