So basically, I will have an array something like this..
<?php
$array = array(
'Actual Hours' => 'http://www.example.com/actual',
'Algorithm' => 'http://www.example.com/algorithm',
'Time Clock App' => 'http://www.example.com/time',
);
echo '<pre>';
print_r($array);
exit;
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 ..
As you can see, I want the first letter of the array key and want to sort it by adding a new key and sort it by that way.
I have researched it but haven't found any solution or suggestion.
Can someone guide me how can I achieve this.
Thanks
CodePudding user response:
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;
CodePudding user response:
Loop, get the first letter 0
of the key string and add to that with the whole key:
foreach($array as $k => $v) {
$result[strtoupper($k[0])][$k] = $v;
}