Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

php - Group rows by one column, only create deeper subarrays when multiple rows in group

I have a multi-dimensional array like this:

Array
(
    [0] => Array
        (
            [id] => 1
            [email_id] => [email protected]
            [password] => test
        )

    [1] => Array
        (
            [id] => 2
            [email_id] => [email protected]
            [password] => test
        )

    [2] => Array
        (
            [id] => 3
            [email_id] => [email protected]
            [password] => pass
        )

)

In the above array, password value is the same in two different rows. I need to merge the arrays which have duplicate values to get the following output:

Array
(
     [0] => Array
            (
               [0] => Array
                (
                    [id] => 1
                    [email_id] => [email protected]
                    [password] => test
                )
        
            [1] => Array
                (
                    [id] => 2
                    [email_id] => [email protected]
                    [password] => test
                )
            ) 
    [1] => Array
        (
            [id] => 3
            [email_id] => [email protected]
            [password] => pass
        )

)

How to do this? I've tried array_merge() & foreach() loops, but I can't get this output.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try,

$arr = array( array('id'=>1, 'email_id'=>'[email protected]', 'password'=>'test'),
  array('id'=>2, 'email_id'=>'[email protected]', 'password'=>'test'), 
  array('id'=>3, 'email_id'=>'[email protected]', '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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...