Search code examples
phparraysgrouping

Group array data by first character and create subarrays in each group


I have an array something like this:

$array = array(
    'Actual Hours' => 'http://www.example.com/actual',
    'Algorithm' => 'http://www.example.com/algorithm',
    'Time Clock App' => 'http://www.example.com/time',
)

And I want the output something like this:

Array
(
    [A] => [
        [Actual Hours] => http://www.example.com/actual
        [Algorithm] => http://www.example.com/algorithm
    ],
    [T] => [
        [Time Clock App] => http://www.example.com/time        
    ],
    
)

So basically I want something like this ..

enter image description here

As you can see, I want the first letter of the array key and want to sort it by adding a new key and group it that way.


Solution

  • Here you go !

    
    $array = array(
        'Actual Hours' => 'http://www.example.com/actual',
        'Algorithm' => 'http://www.example.com/algorithm',
        'Time Clock App' => 'http://www.example.com/time',
    
    );
    
    $new_array = [];
    foreach( $array as $key => $value ) {
        $char = strtoupper(substr($key,0,1));
        if(!array_key_exists( $char, $new_array)) {
            $new_array[$char] = [];
        }
        $new_array[$char][$key] = $value;
    }
    
    $array = $new_array;