Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...