Jump to content

need multi dimensional array help


bulmer

Recommended Posts

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.

Link to comment
Share on other sites

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 ;D

 

Link to comment
Share on other sites

Thanks MMDE and gizmola, that did the trick with a lot less code than I imagined.. :o

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.