开发者

How can i put my database result in 3 dimensional array?

This is my code

mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");

is there any way to extract title,text,date from $result and put them into 3 d开发者_如何学Cimensional array?


What about

$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;

while( $row = mysql_fetch_assoc( $result ) {
    $array[$i] = array();
    // i'm just guessing at what sort of array you want
    $array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
    $i++;
}


I'd be interested to know what the ... you need a three-dimensional array for but ok:

$dim = array();

$result = mysql_query(...);

while ( $row = mysql_fetch_assoc($result) )
    // Whatever you want to save in that particular bucket,
    // I'll be using the result set
    $dim[$row['title']][$row['text']][$row['date']] = $row;

Strange, ...


If we are already guessing, here is mine:

$results = array();

while(($row = mysql_fetch_assoc($result))) {
    $results[] = $row;
}

which will create an array like this:

array(array('title' => 'foo',
            'text' => 'bar',
            'date' => 'baz'),
      //...
)


I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)

One of the comments under the documentation of mysql_fetch_array has an answer to this:

(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)

<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $i=0;
  $keys=array_keys(mysql_fetch_array($result, $numass));
  mysql_data_seek($result, 0);
    while ($row = mysql_fetch_array($result, $numass)) {
      foreach ($keys as $speckey) {
        $got[$i][$speckey]=$row[$speckey];
      }
    $i++;
    }
  return $got;
}
?>

You should then be able to use this function as

<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");

$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜