-
PHP合并某个字段相同的数组,并重组数据算法
- 对数组$array重组:
-
-
- $array = array(
- array('id'=>1,'name'=>'aa','pwd'=>'12'),
- array('id'=>1,'name'=>'bb','pwd'=>'56'),
- array('id'=>1,'name'=>'saa','pwd'=>'89'),
-
- array('id'=>2,'name'=>'cc','pwd'=>'78')
- );
- 实现代码如下:
-
- $tmpArray = array();
- foreach ($array as $row) {
-
- $key = $row['id'];
- if (array_key_exists($key, $tmpArray)) {
-
- if (is_array($tmpArray[$key]['name'])) {
- $tmpArray[$key]['name'][] = $row['name'];
- } else {
- $tmpArray[$key]['name'] = array($tmpArray[$key]['name'], $row['name']);
- }
- if (is_array($tmpArray[$key]['pwd'])) {
- $tmpArray[$key]['pwd'][] = $row['pwd'];
- } else {
- $tmpArray[$key]['pwd'] = array($tmpArray[$key]['pwd'], $row['pwd']);
- }
- } else {
- $tmpArray[$key] = array('id'=>$row['id'],'name'=>array($row['name']),'pwd'=>array($row['pwd']));
-
- }
- }
-
- echo "<pre>";
- var_dump($tmpArray);
-
- 打印结果为:
-
- array (size=2)
- 1 =>
- array (size=3)
- 'id' => int 1
- 'name' =>
- array (size=3)
- 0 => string 'aa' (length=2)
- 1 => string 'bb' (length=2)
- 2 => string 'saa' (length=3)
- 'pwd' =>
- array (size=3)
- 0 => string '12' (length=2)
- 1 => string '56' (length=2)
- 2 => string '89' (length=2)
- 2 =>
- array (size=3)
- 'id' => int 2
- 'name' =>
- array (size=1)
- 0 => string 'cc' (length=2)
- 'pwd' =>
- array (size=1)
- 0 => string '78' (length=2)
-
- public function combine($array,$field){
- $tmpArray = array();
- $distinct_field = $field[0];
- unset($field[0]);
- foreach ($array as $row) {
- $key = $row[$distinct_field];
- if (array_key_exists($key, $tmpArray)) {
- foreach($field as $value){
- if (is_array($tmpArray[$key][$value])) {
- $tmpArray[$key][$value][] = $row[$value];
- } else {
- $tmpArray[$key][$value] = array($tmpArray[$key][$value], $row[$value]);
- }
- }
- } else {
- $tmpArray[$key][$distinct_field] = $row[$distinct_field];
- foreach ($field as $value){
- $tmpArray[$key][$value] = array($row[$value]);
- }
- }
- }
- return $tmpArray;
- }
-
相关阅读:
MySQL基础(3):进阶用法
MySQL基础(2):DDL语言
MySQL基础(1):基本语法
Linux中配置ftp传输
Eclipse插件安装的三种方法
C++中string,wstring,CString的基本概念和用法
程序员的谈判技巧
转:C++编程隐蔽错误:error C2533: 构造函数不能有返回类型
CMake入门以及学习笔记
程序员的学习方法
-
原文地址:https://www.cnblogs.com/chen1970s/p/7728042.html
Copyright © 2020-2023
润新知