Paddy Hallihan
Paddy Hallihan

Reputation: 1686

Create multidimensional array from database query in PHP

I have a database with a number of entries with data like so:

id  number  data
1   1       'tyfvib'
2   1       'fgdhjjd'
3   1       'gdgdhdj'
4   2       'dgfhfh'
5   2       'fghdhd'

So I have a unique ID and then a column with numbers and then a column with different strings.

I then have a query like this:

$sql = "SELECT * FROM table";
$stmt = DB::run($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $number= $row['number'];
    $data = $row['data'];
}

I want to make a multidimensional associative array which would have first of all an array of the unique numbers and these would contain an array of the data associated with them.

I had tried putting $array[$number] = $data inside the while loop but this obviously will just make an array where the only data associated with a number is the last one in the loop.

Upvotes: 4

Views: 4929

Answers (2)

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

you need to create a array variable before your loop where you can push your data on each iteration as

$alldata=[]
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $alldata[$row['number']][] = $data
}
echo"<pre>";print_r($alldata);

Upvotes: -1

misorude
misorude

Reputation: 3431

I had tried putting $array[$number] = $data inside the while loop but this obviously will just make an array where the only data associated with a number is the last one in the loop.

Then add an additional set of []:

$array[$number][] = $data;

will create a new entry in the array $array[$number] each time.

Upvotes: 5

Related Questions