PHP合並某個字段相同的數組,並重組數據算法
阿新 • • 發佈:2017-10-25
算法 字數 class tinc 字符串 urn keyword pub _array
- 對數組$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)) {
- //$tmpArray[$key][‘pwd‘] = $tmpArray[$key][‘pwd‘] . ‘,‘ . $row[‘pwd‘]; //用這句的話下面有關pwd的條件語句都要刪掉,實現其字符串形式
- 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‘])); //此句要註意,可設置
- // $tmpArray[$key] = $row; // 有字段相加時可能會代替上面一句
- }
- }
- 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)
- // $field 為一維數字數組,$field[0]為用於分組的單一字段。
- 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;
- }
PHP合並某個字段相同的數組,並重組數據算法