使用列名和值从mysql创建数组

时间:2013-11-07 17:23:21

标签: php mysql arrays

我正在尝试使用PHP和MySQL创建一个数组,但我总是会遇到错误。

我正在使用的代码

function db_listar_usuarios(){
$link=db_connect();
$query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
$result = $link->query($query);
  while($row = mysqli_fetch_assoc($result)) {   
        echo $row['nombre'] . array(;
        foreach ($row as $col => $val) {
           $col => $val;
        }
        echo "\n\n############\n";
    }
}

我想用这段代码创建的是:

array(
    'john' => array('address' => 'st 123', 'age' => '25', 'surname' => 'doe'),
    'ane' => array('address' => 'av 456', 'age'=> '32', 'surname' => 'smith'),
);

然后使用像这样的东西:

private $contacts = db_listar_usuarios();

提前谢谢你:)

2 个答案:

答案 0 :(得分:1)

function db_listar_usuarios(){
$link=db_connect();
$query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
$result = $link->query($query);
  while($row = mysqli_fetch_assoc($result)) {   
        echo $row['nombre'] . array(; // <- invalid in several ways
        foreach ($row as $col => $val) {
           $col => $val;
        }
        echo "\n\n############\n";
    }
}

尝试:

function db_listar_usuarios(){
    $link = db_connect();
    $query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
    $result = $link->query($query);
    $myArray = array();
    while($row = mysqli_fetch_assoc($result)) {   
        $myArray[] = $row;
        print_r($myArray); // for debugging
        echo "\n\n############\n";
    }
    return $myArray;
}

答案 1 :(得分:1)

$users = array();
while($row = mysqli_fetch_assoc($result)) {            
    foreach ($row as $col => $val) {
        $users[$col] = $val;
    }
}
print_r($users);