DavidM
DavidM

Reputation: 23

How to rationalise a multidimensional array in php?

I've been trying this all day! How would I convert the top multidimensional array into the bottom.

Array (
[0] => Array ( [id] => 34 [email] => [email protected] ) 
[1] => Array ( [id] => 34 [email] => [email protected] ) 
[2] => Array ( [id] => 33 [email] => [email protected] ) 
[3] => Array ( [id] => 33 [email] => [email protected] ) 
[4] => Array ( [id] => 33 [email] => [email protected] ) 
) 

Array (
[0]=>Array ([id] => 34 [email] => Array ([0]=> [email protected] [1]=>[email protected] )
[1]=>Array ([id] => 33 [email] => Array ([0]=> [email protected] [1]=>[email protected] [2]=>[email protected])
)

Many thanks.

Upvotes: 0

Views: 84

Answers (2)

Victor Vasiliev
Victor Vasiliev

Reputation: 462

Would not just using keys in order to store IDs be an easier way to do that? Like this:

Array (
[34]=>Array ([email] => Array ([0]=> [email protected] [1]=>[email protected] )
[33]=>Array ([email] => Array ([0]=> [email protected] [1]=>[email protected] [2]=>[email protected])
)

Then grouping emails would become a trivial task.

Upvotes: 1

Marc B
Marc B

Reputation: 360702

$new_array = array();
foreach ($orig_array as $child) {
    $new_array[$child['id']][] = $child['email'];
}

$final_array = array();
foreach($new_array as $child) {
   $final_array[] = $child;
}

The first loop produces an array keyed off the id fields, and simply pushes each email address onto it. The second loop then takes that intermediate array and wraps another array around it for the 0,1,etc... keys.

Upvotes: 1

Related Questions