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 Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/ 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. Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/#findComment-1554825 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; } Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/#findComment-1554826 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. Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/#findComment-1554829 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. Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/#findComment-1554830 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)); } Quote Link to comment https://forums.phpfreaks.com/topic/305956-text-string-to-array/#findComment-1554831 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.