开发者

Mysql results into array (PHP)

How can i convert mysql results (from mysql_fetch_array) into such a form?

$some = array(
     "comments" => array(
         array( "text" => "hi", "id" => "1" ),
         array( "text" => "hi", "id" => "2" ),
         array( "text" => "hi", "id" => "3" ),
         array( "text" => "hi", "id" => "4" )
    )
);

while the db looks like:

comments

id  text
1   blabla bla
2  开发者_如何学编程 bla bla

i've tried to fetch the values with foreach/while and insert it into two arrays but no success...

$some = array(
    "comments" => array()
);

$q = $mysql->sf('*', TBL_QST);
foreach($mysql->fetch($q) as $row) {
    $some[] = $row;
    // $some["comments"][] = $row;
}


My print_r gives:

Array
(
    [comments] => Array
        (
            [0] => Array
                (
                    [text] => lorem ipsum
                    [id] => 0
                )
            [1] => Array
                (
                    [text] => lorem ipsum
                    [id] => 1
                )
            [2] => Array
                (
                    [text] => lorem ipsum
                    [id] => 2
                )
        )
)

And the php I did for it is:

$comments = array(
    'comments' => array()
    );

/* To simualate the loop */
for ($i = 0; $i < 3; $i++) { 
    array_push($comments['comments'], array(
        'text' => 'lorem ipsum',
        'id' => $i
        )
    );
}

I hope this will be to any help and that I didn't misunderstood your question.


Use mysql_fetch_assoc() instead, or use MYSQL_ASSOC as second argument of mysql_fetch_array().


Here's what I would do:

$dbc = mysql_connect(SERVER, USERNAME, PASSWORD);
mysql_select_db($dbc, DATABASE);

$query = "SELECT `id`, `text` FROM `comments`";
$result = mysql_query($dbc, $query);

$some = Array("comments" => Array());
while($row = mysql_fetch_array($result)) {
    array_push($some['comments'], Array($row['id'], $row['text']));
}


$some['comments'][] = ...

inside a loop


What you want is an associative array, and for this reason a special function has been already developed in PHP which is called mysql_fetch_assoc().

Updated
I am sorry, I understood you wrong. In this case you need this block of code below.

$sql="select id,text from comments";
$res=mysql_query($sql);
$arr=array();
while($row=mysql_fetch_assoc($res)){
     $arr[]=array('id'=>$row['id'],'text'=>$row['text']);
}
$some=array('comments'=>$arr);


Make an array with the same structure as the comments table:

$results = mysql_query("SELECT `id`, `text` FROM `comments`");
while ($row = mysql_fetch_array($results, MYSQL_NUM)) {$comments[intval($row[0])] = $row[1];}

The comments array is now structured:

comments[int `id`]=>`comment`

Then if you need comments in the "some" array:

$some['comments'] = $comments;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜