一般从数据库中提取数据时,会遇到各种各样类型的数据,要求也不尽相同。自己这两天开发的时候遇到一个很纠结的问题,如下:
比如一个二维数组是这样的:
Array (
[0] => Array (
[uid] => 231
[username] => 123456
[active] =>aaaa
[transfer] =>1111
)
[1] => Array (
[uid] => 231
[username] =>123456
[active] => bbbb
[transfer] =>2222
)
[1] => Array (
[uid] => 231
[username] =>123456
[active] => cccc
[transfer] => 3333
)
)
想让二维数组相同字段的数据合并到一起。效果如下:
array(
[uid] => 231
[username] => 123456
[active] =>array(
aaaa,
bbbb,
cccc
)
[transfer] =>array(
1111,
2222,
3333
)
)
function arr_rmar($array) {
$temp = array ();
foreach ( $array as $k => $v ) {
$temp [$k] = $v ['uid'];
}
$temp = array_merge ( array_unique ( $temp ) );
$temp2 = array ();
for($i = 0; $i < count ( $temp ); $i ++) {
$temp1 = array ();
foreach ( $array as $k1 => $v1 ) {
if ($v1 ['uid'] === $temp [$i]) {
$temp1 ['username'] = $v1 ['username'];
$temp1 ['active'] [] = $v1 ['active'];
$temp1 ['transfer'] [] = $v1 ['transfer'];
}
}
}
$temp2 [] = $temp1;
}
return $temp2;
}
调用这个函数就可以。下面代码字段必须要和数组中的一样,还要注意需要合并的选项后面要价“[]”符号用来区分是否是数组。这也是这个函数的局限性,如果有更好的意见可以大家分享。