合并多维数组php中的重复数组值

时间:2013-01-07 18:46:18

标签: php arrays

我有一个多维数组说,

Array
(
    [0] => Array
        (
            [id] => 1
            [email_id] => ok@gmail.com
            [password] => test
        )

    [1] => Array
        (
            [id] => 2
            [email_id] => check@gmail.com
            [password] => test
        )

    [2] => Array
        (
            [id] => 3
            [email_id] => an@gmail.com
            [password] => pass
        )

)

在上面的数组中,密码键在两个键中具有相同的值,我需要合并具有重复值的数组以获得以下输出,

Array
(
     [0] => Array
            (
               [0] => Array
                (
                    [id] => 1
                    [email_id] => ok@gmail.com
                    [password] => test
                )

            [1] => Array
                (
                    [id] => 2
                    [email_id] => check@gmail.com
                    [password] => test
                )
            ) 
    [1] => Array
        (
            [id] => 3
            [email_id] => an@gmail.com
            [password] => pass
        )

)

怎么做?我试过array_merge& foreach循环,但我无法获得此输出

1 个答案:

答案 0 :(得分:1)

尝试,

$arr = array( array('id'=>1, 'email_id'=>'ok@gmail.com', 'password'=>'test'),
  array('id'=>2, 'email_id'=>'check@gmail.com', 'password'=>'test'), 
  array('id'=>3, 'email_id'=>'an@gmail.com', 'password'=>'pass'));

  $new_arr = array();
  foreach($arr as $k => $v) {
      if( is_array($arr[$k+1]) && $arr[$k]['password'] === $arr[$k + 1]['password'] )
          $new_arr[] = array($arr[$k], $arr[$k+1]);
      else if( in_array_recursive($arr[$k]['password'], $new_arr) === FALSE ) 
              $new_arr[] = $v;
  }

  function in_array_recursive( $val, $arr) {
      foreach( $arr as $v ) {
          foreach($v as $m) {
              if( in_array($val, $m ) )
                  return TRUE;      
          }
      }
      return FALSE;
  }

  print_r($new_arr);

Demo