Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explode multidimensional array with key and value

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

like image 882
Stfvns Avatar asked Jul 23 '26 19:07

Stfvns


2 Answers

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"
  }
}
like image 150
Jakub Matczak Avatar answered Jul 26 '26 09:07

Jakub Matczak


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]
});
like image 22
Matt S Avatar answered Jul 26 '26 09:07

Matt S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!