Jump to content

[SOLVED] mysql 3d array in php


c172cpt

Recommended Posts

i need help i cant figure out how to create a 3d array in php from a mysql query

 

the query is:

select name, file from images order by rand() limit 0,18

 

this gives me 18 random rows from the db and i i can sort though all of it with mysql_fetch_array but only one row at a time

what i want is all the data at once

eg.

$answer['row#']['name']['data']

$answer['row#']['file']['data']

 

essentially i want 36 variables from the one mysql query

 

thanks,

 

-scott-

Link to comment
https://forums.phpfreaks.com/topic/81827-solved-mysql-3d-array-in-php/
Share on other sites

Hmm... Something like this?

 

<?php

$query = "SELECT name, file FROM images ORDER BY RAND() LIMIT 0,18";
$result = mysql_query($query);

$row = 0;
while ($record = mysql_fetch_assoc($result)) {
    $answer[$idx]['name'] = $record['name'];
    $answer[$idx]['file'] = $record['file'];
    $row++;
}
?>

This should work as well, but I like th one above better as it is apparent exactly what variables are being set. But this one should be a little faster if speed becomes an issue.

 

[code]<?php

$query = "SELECT name, file FROM images ORDER BY RAND() LIMIT 0,18";
$result = mysql_query($query);

while ($record = mysql_fetch_assoc($result)) {
    $answer[] = $record;
}
?>

[/code]

When I was working out my 3d array issue, I tried something similiar to this, but it would only use the last entry instead of building a multi demension array.  I ended up doing something like your first example, it seemed more reliable and results were as expected.

 

This should work as well, but I like th one above better as it is apparent exactly what variables are being set. But this one should be a little faster if speed becomes an issue.

 

[code]<?php

$query = "SELECT name, file FROM images ORDER BY RAND() LIMIT 0,18";
$result = mysql_query($query);

while ($record = mysql_fetch_assoc($result)) {
    $answer[] = $record;
}
?>

[/code]

The second code I posted will result in the exact same array. The fact that you had a problem previously has nothing to do with that proposed method.

 

Did you remember to put the empty brackets when declaring the value? That is what ensures that a new array item is created.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.