首页 >后端开发 >php教程 > php数结合并 高手挑战

php数结合并 高手挑战

WBOY
WBOY原创
2016-06-13 13:22:40847浏览

php数组合并 高手挑战
将以下数组合并为一个数组
Array
(
  [0] => Array
  (
  [id] => default
  [name] => aaa
  [tel] => bbb
  [age] => ccc
  )

  [1] => Array
  (
  [id] => 11
  [name] => aaa
  [tel] => bbb
  [age] => ccc
  )

  [2] => Array
  (
  [id] => 22
  [name] => aaa
  [tel] => bbb
  [age] => ccc
  )

  [3] => Array
  (
  [id] => 33
  [name] => aaa
  [tel] => bbb
  [age] => ccc
  )

  [4] => Array
  (
  [id] => 44
  [name] => new
  [tel] => eee
  [age] => fff
  )

  [5] => Array
  (
  [id] => 66
  [name] => new
  [tel] => eee
  [age] => fff
  )

)


将以上数组合并为下面的数组

Array
(
  [0] => Array
  (
  [id] => array(
  [0] => default
  [1] => 11
  [2] => 22
  [3] => 33
  )
  [name] => aaa
  [tel] => bbb
  [age] => ccc
  )

  [1] => Array
  (
  [id] => array(
  [0] => 44,
  [1] => 66
  )
  [name] => new
  [tel] => eee
  [age] => fff
  )

)

------解决方案--------------------

PHP code
$ar = array (
  0 => 
  array (
    'id' => 'default',
    'name' => 'aaa',
    'tel' => 'bbb',
    'age' => 'ccc',
  ),
  1 => 
  array (
    'id' => '11',
    'name' => 'aaa',
    'tel' => 'bbb',
    'age' => 'ccc',
  ),
  2 => 
  array (
    'id' => '22',
    'name' => 'aaa',
    'tel' => 'bbb',
    'age' => 'ccc',
  ),
  3 => 
  array (
    'id' => '33',
    'name' => 'aaa',
    'tel' => 'bbb',
    'age' => 'ccc',
  ),
  4 => 
  array (
    'id' => '44',
    'name' => 'new',
    'tel' => 'eee',
    'age' => 'fff',
  ),
  5 => 
  array (
    'id' => '66',
    'name' => 'new',
    'tel' => 'eee',
    'age' => 'fff',
  ),
);

$res = array();
foreach($ar as $r) {
  $k = "$r[name]--$r[tel]--$r[age]";
  if(! isset($res[$k])) {
    $res[$k] = $r;
    $res[$k]['id'] = array();
  }
  $res[$k]['id'][] = $r['id'];
}
$res = array_values($res);
print_r($res); <div class="clear">
                 
              
              
        
            </div>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn