Php将记录转化为二维数组



我想从数据库中获取记录,而不是转换为二维数组。

Example:
$data = array(
        1 => array ('Name', 'Surname','sex','address','web'),
        array('Schwarz', 'Oliver','M','KP','222.dddd'),
        array('Test', 'Peter','F','KK','wwww.fsadfs')
        );

如何格式化数据库中的数据,如上图所示?

这里有一个例子,使用PDO和在粘贴本身内部创建的内存中SQLite数据库;必须在线创建数据库会使脚本比严格要求的更加详细。

试试这样的东西:

$i = 0;
foreach( $results as $result )
{
    $array[$i]['field1'] = $results['field1'];
    $array[$i]['field2'] = $results['field2'];
    $i++;
}

根据您用来访问数据库的库,它可能略有不同。

以下是创建函数的答案,返回多个数组

public static function getRecords($query){  // Gets multiple records and    returns associative array
    $db = db::open();
    $result = $db->query($query);
    if(!$result){
        die('There was an error running the query [' . $db->error . ']');
    }
    if($result->num_rows>0){
        $i=0;
        while ($row = $result->fetch_assoc()){
            $recordset[$i] = $row;
            $i++;
            }
        }else{
            $recordset = false;
        }
    db::close($db);
    return ($recordset);
}

你只需要像一样通过查询

 $QUERY="select * FROM USERS";

AND CREATE class db to open the connection and also add function in this class and your function is ready 

    class db{
    public static function open(){ // opens the db connection. Specify different databases for local and live server and it will automatically select the correct one
       $servers = array('localhost', '127.0.0.1', 'warrior');
        if(in_array($_SERVER['HTTP_HOST'], $servers)){ //for localhost
            $dbuser = 'root';
            $dbpwd = '';
            $dbname = 'database name';
            $dbserver = 'localhost';
        }
        $db = mysqli_connect($dbserver,$dbuser,$dbpwd,$dbname);
        if ($db->connect_errno > 0){
          echo "Failed to connect to MySQL: " . $db->connect_error;
          }
         return $db;
        }
    public static function close(&$db){
        $db->close();
    } //also add your Get_record function here
}

包含文件并对其进行测试感谢

相关内容

  • 没有找到相关文章

最新更新