php 将php结果集转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8515191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:53:43  来源:igfitidea点击:

Convert a php resultset into an array

phparraysresultset

提问by Kannan Lg

I am trying to convert a php resultset into an array (using foreach), I'm not quite doing it right..

我正在尝试将 php 结果集转换为数组(使用 foreach),但我做得不太对。

I have a resultset:

我有一个结果集:

$result

I am looping through it as below: (horribly wrong)

我循环如下:(大错特错)

while($row = mysql_fetch_array($result)) {

    foreach (mysql_fetch_array($result) as $k => $v) {
      echo "Fred's $k is ". $v['uid']. "\n";
    }

}

I want this array to be in the below format:

我希望这个数组采用以下格式:

Array
(
    [0] => Array    //row1
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .

        )

    [1] => Array    //row2
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .
        )

    [2] => Array    //row3
        (
            [column1] => value
            [column2] => value
            [column3] => value
        .
        .
        )

)

I am a newbie, please help.

我是新手,请帮忙。

回答by Shoogle

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

    //$results has all that you need
    print_r($results);

回答by Jake Lucas

You don't need a foreach to do this, you can just stick with your while loop:

你不需要 foreach 来做到这一点,你可以坚持你的 while 循环:

$result_set = array();

while($row = mysql_fetch_array($result)) {
    $result_set[] = $row;
}

Then you can use it like a normal array:

然后你可以像普通数组一样使用它:

$result_set[0]['column_name'];

回答by Ayman Safadi

Try mysql_fetch_associnstead:

尝试mysql_fetch_assoc代替:

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

回答by adatapost

Try this,

尝试这个,

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

回答by jogesh_pi

i can't understand well but hope this will help you :

我不太明白,但希望这会帮助你:

$array = array();
while($row = mysql_fetch_array($result)) {
 $array[] = $row['uid'];
}