I have a form where you type in different movies and separate them with "|". The database currently contains:
Spider-man|Spider-man 2|Spider-man 3|Apple|Google|Banana|Citrus
I have done an explode() of this text string so each title goes into an array:
$collection = explode('|', $collection);
For the sake of keeping things sorted alphabetically, I did this:
array_multisort($collection);
So far it's alright. However, now I need to make this array multidimensional with each key corresponding the letter the values start with. It should become like this:
Array(
[A] => Array(
'Apple'
)
[B] => Array(
'Banana'
)
[C] => Array(
'Citrus'
)
[G] => Array(
'Google'
)
[S] => Array(
'Spider-man',
'Spider-man 2',
'Spider-man 3'
)
)
How can I achieve this?
Thanks in advance, Filip
Not the way you should be storing things in the database. You should have a table that relates to that one that holds the movies each in its own row. That being said:
//array_multisort($collection); // don't need this
sort($collection);
foreach($collection as $movie) {
$result[$movie[0]][] = $movie;
}
If there might be some movies that start with a lowercase letter, then:
foreach($collection as $movie) {
$result[strtoupper($movie[0])][] = $movie;
}
ksort($result);
There is no built-in
function for that. You need to craft something on your own. Like this:
$string = 'Spider-man|Spider-man 2|Spider-man 3|Apple|Google|Banana|Citrus';
$result = array();
foreach(explode('|', $string) as $item) {
$firstLetter = $item[0];
if(!isset($result[$firstLetter])) {
$result[$firstLetter] = array();
}
$result[$firstLetter][] = $item;
}
ksort($result);
var_dump($result);
$input = 'Spider-man|Spider-man 2|Spider-man 3|Apple|Google|Banana|Citrus';
$collection = array();
$movies = explode('|', $input);
sort($movies);
foreach ($movies as $movie) {
$collection[strtoupper($movie[0])][] = $movie;
}
print_r($collection);