- 对数组$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;
- }
|
请发表评论