jonnyenglish89 Posted December 21, 2017 Share Posted December 21, 2017 Hey guys how can i use php to turn a string like this: “A, B#2, C#2, D#3, E” Into an array like this: Array ( [1] => A [2] => B [3] => B [4] => C [5] => C [6] => D [7] => D [8] => D [9]=> E ) I can get the letter and count into an array like this with the help of regex: Array ( [A] => 1 => 2 [C] => 2 [D] => 3 [D]=> 1 ) But I have no idea how I would get the result I desire – any help with this part would be greatly appreciated Link to comment Share on other sites More sharing options...
requinix Posted December 21, 2017 Share Posted December 21, 2017 Set up a new empty array to hold the final result. Do a foreach on your regex array, then do a for loop according to each letter's count. Inside the for loop, add the letter to the final result array. Link to comment Share on other sites More sharing options...
Barand Posted December 21, 2017 Share Posted December 21, 2017 or awhile loop instead of a for loop $input = [ 'A' => 1, 'B' => 2, 'C' => 2, 'D' => 3, 'E' => 1 ]; $output = []; foreach ($input as $k => $n) { while ($n--) $output[] = $k; } Link to comment Share on other sites More sharing options...
benanamen Posted December 21, 2017 Share Posted December 21, 2017 Where and how does your string come from in the first place. I smell an XY Problem. Link to comment Share on other sites More sharing options...
ginerjm Posted December 21, 2017 Share Posted December 21, 2017 I agree with Benanamen - Seems like a rather silly goal to get an array like the one the OP describes. Link to comment Share on other sites More sharing options...
Psycho Posted December 21, 2017 Share Posted December 21, 2017 Another way: foreach ($input as $k => $n) { $output = array_merge($output, array_fill(0, $n, $k)); } Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.