开发者

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 开发者_JS百科(
[0] => Array ( [id] => 34 [email] => a@example.com ) 
[1] => Array ( [id] => 34 [email] => b@example.com ) 
[2] => Array ( [id] => 33 [email] => c@example.com ) 
[3] => Array ( [id] => 33 [email] => d@example.com ) 
[4] => Array ( [id] => 33 [email] => e@example.com ) 
) 

Array (
[0]=>Array ([id] => 34 [email] => Array ([0]=> a@example.com [1]=>b@example.com )
[1]=>Array ([id] => 33 [email] => Array ([0]=> c@example.com [1]=>d@example.com [2]=>e@example.com)
)

Many thanks.


$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.


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]=> a@example.com [1]=>b@example.com )
[33]=>Array ([email] => Array ([0]=> c@example.com [1]=>d@example.com [2]=>e@example.com)
)

Then grouping emails would become a trivial task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜