bulmer Posted February 13, 2012 Share Posted February 13, 2012 I have been trying to solve this problem for a few days now and can't seem to work it out. I'm sure i'm missing some simple point.. I am using a mysql PDO fetch to return 2 fields in each row and then put them into an array of their own: foreach ($st->fetchAll() as $row){ $subs[] = array($row['subscriber'],$row['plant']); Some of the rows share the same $row[0], which is the 'subscriber' field. What I want to do is make up another array with each smaller array having a single, unique $row[0] and any number of added 'plant' fields following (e.g $row[1],$row[2] etc). I've tried all sorts of ways to achieve this but am at a loss. Would someone be able to point me in the right direction ? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/257005-need-multi-dimensional-array-help/ Share on other sites More sharing options...
MMDE Posted February 13, 2012 Share Posted February 13, 2012 foreach ($st->fetchAll() as $row){ $subs[$row['subscriber']][] = $row['plant']; } Maybe this would do it? Quote Link to comment https://forums.phpfreaks.com/topic/257005-need-multi-dimensional-array-help/#findComment-1317501 Share on other sites More sharing options...
gizmola Posted February 13, 2012 Share Posted February 13, 2012 bulmer, You will have more luck using the php tags around your code. I edited your post this time to help you out. [code=php:0] // [/code] I'm not sure I completely understand what you are trying to do or why, but it's important to keep in mind that the major strength of php arrays is that they are associative (keyed by string). So let's say that you wanted to build a 2 dimensional array by subscriber, if I understand you correctly. Try this: foreach ($st->fetchAll() as $row) { $subs[$row['subscriber']][] = $row['plant']; } var_dump($subs); The first dimension will be keyed by the subscriber values. The 2nd dimension will be an array of 1-Many plants. Based on your description this might be what you're looking for. *update* Notice MMDE suggested the same thing Quote Link to comment https://forums.phpfreaks.com/topic/257005-need-multi-dimensional-array-help/#findComment-1317502 Share on other sites More sharing options...
bulmer Posted February 13, 2012 Author Share Posted February 13, 2012 Thanks MMDE and gizmola, that did the trick with a lot less code than I imagined.. So if I understand correctly it uses the first field as the key in the main array, creates a new empty array under it and numerically appends all 'plant' fields to it that have that same key? By the way i've always found this site to be a great help and resource, keep up the good work.Cheers. Quote Link to comment https://forums.phpfreaks.com/topic/257005-need-multi-dimensional-array-help/#findComment-1317510 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.