Saqlain Syed - 1 year ago 50

PHP Question

I am working on associative arrays from two days, but somehow could not reach to my answer. I am using for loop for this, let me know if there some better approach to do this.. let suppose I have an associative array like below

`$students = array('a' => 84 , 'b' => 92 , 'a' => 93 , 'b' => 47 , 'c' => 73 ,`

'd' => 59 , 'e' => 91 , 'a' => 78 , 'c' => 85 ,'e' => 68 ,

'c' => 84 , 'a' => 100 ,'d' => 92 , 'e' => 85 , 'd' => 83 ,

'a' => 92 , 'b' => 68 , 'b' => 79 ,'d' => 79 , 'a' => 84 ,

'b' => 89 , 'c' => 69 , 'c' => 67 ,'c' => 92 , 'd' => 73 ,

'e' => 79 , 'e' => 84);

and I want this array to convert into a multidimensional array, take all values of 'a' and put this into an array 'a' and apply the same rule for the rest like given below.

The out put should be like.

`$students = array('a' => array(84, 93, 88, 100, 92, 84),`

'b' => array(92, 47, 68, 79, 89),

'c' => array(73, 85, 84, 69, 67, 92),

'd' => array(59, 92, 83, 79, 73),

'e' => array(91, 68, 85, 79, 84));

How should I do this ? Thanks :)

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Something like this? https://eval.in/626246

```
<?php
$students = [
['a', 84], ['b', 47], ['c', 73],
['a', 92], ['a', 93], ['b', 68],
];
$groups = [];
foreach ($students as list($class, $number)) {
$groups[$class][] = $number;
}
ksort($groups);
foreach ($groups as &$numbers) {
sort($numbers);
}
unset($numbers); // Do not forget unsetting variable reference
print_r($groups);
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**