创建多维数组。

时间:2014-04-24 05:08:41

标签: php arrays multidimensional-array associative-array

如何从数据库结果集中创建PHP中的以下数组。

Array (
 [0] => Array ( [id] => 1 [name] => Little Hacienda [is_open] => 0 [order] => 0 )
 [1] => Array ( [id] => 2 [name] => testcat [is_open] => 0 [order] => 0 )
 [2] => Array ( [id] => 3 [name] => fgf [is_open] => 0 [order] => 0 )
 )

我有以下代码,

$arr = array();
$r = mysql_query("SELECT * FROM categories WHERE id=".$key."");
    if (mysql_num_rows($r) > 0){
        $row = mysql_fetch_assoc($r);
        $f = mysql_num_rows($r);
        for($j = 0; $j < count($f); $j++){
            $arr[$j] = $row[$f[$j]['field']];               

        }
    }
         $test = array();
     array_push($test, $arr);
     return $test;

但这会返回数组

Array ( [0] => Array ( [0] => 1 [1] => Little Hacienda [2] => 0 [3] => 0 ) ) 

任何帮助将不胜感激..

2 个答案:

答案 0 :(得分:0)

你可以这样做:

$arr = array();
$r = mysql_query("SELECT * FROM categories WHERE id='".$key."'");
if (mysql_num_rows($r) > 0) {
    $row = mysql_fetch_assoc($r);
    $i = 0;
    while ($row = mysql_fetch_assoc($r)) {
        $arr[$i] = $row;
        ++$i;
    }
}
$test = array();
array_push($test, $arr);
return $test;

答案 1 :(得分:0)

尝试:

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

但我不能在没有义务的情况下离开&#34; You shouldn't be using a deprecated library&#34;。

不推荐使用Mysql库,不应再使用它。请查看使用MySQL PDO(一个不错的OOP界面)或Mysqli library