I have a string like this:
$string = Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike
What I've done:
$explode = ("; ", $string);
Then it will show like:
Array ([0] => Leader,Brian [1] => Elder,Nina,Maria [2] => Member,Duke,Rai,Mike)
But I don't like that. I want to make a multidimensional array with key and value, like this:
Array ([Leader] => Brian [Elder] => Array ([0] => Nina [1] => Maria)
[Member] => Array ([0] => Duke [1] => Rai [2] => Mike))
How to show it in table tag html like this?
Leader | Brian
Elder | Nina
| Maria
Member | Duke
| Rai
| Mike
NB: You can change the separator in string if it's difficult with separator like that
Youre explode is a good first step.
Next one is to iterate its result and explode it again.
Then (in the same loop) use first element of the second explode's result as key and the rest as value.
$string = "Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike";
$exploded = explode("; ", $string);
foreach($exploded as $element) {
$arr = explode(',', $element);
$result[array_shift($arr)] = $arr;
}
var_dump($result);
Result:
array(3) {
["Leader"]=>
array(1) {
[0]=>
string(5) "Brian"
}
["Elder"]=>
array(2) {
[0]=>
string(4) "Nina"
[1]=>
string(5) "Maria"
}
["Member"]=>
array(3) {
[0]=>
string(4) "Duke"
[1]=>
string(3) "Rai"
[2]=>
string(4) "Mike"
}
}
I would probably walk the array after splitting the string and split again:
$list = explode("; ", $string);
array_walk($list, function(&$element) {
$names = explode(',', $element);
// Take the first item off the array type
$type = array_shift($names);
// Alter the array in-place to create the sub-array
$element = [$type => $names]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With