2016-11-20 69 views
0

我确定这已经在很多次之前完成了,但我很难找到简单的解决方案,可能是因为我很难围绕它解决问题。上下文是一个自定义的PDO包装器。将MySQL架构导入到PHP关联数组中

摘要:我想制作一个二级阵列schema以两种方式轻松访问一个MySQL表架构(?):

  1. 列类型/空/列名的默认值(类似`模式[ '字段名'] [ '空'])。
  2. 字段数组(可能由array_keys(schema)生成)与array_intersect配合使用来验证查询字段。

详情:

$schema = $pdo->run("DESCRIBE " . $tablename); 
(magic happens here) 
// validate input field array by field names 
$queryfields = array_intersect(array_keys($schema), $inputdata; 
// check format of input data 
foreach ($schema as $column => $key) { 
    if ($column['type'] == 'datetime') { 
    $inputdata[$key] = date_format($inputdata[$key], 'yyyy-mm-dd'); 
    } 
} 

不要太在细节上陷入困境。基本上我想将一个平面数组数组变成相同的东西,但按列名分组。

+0

或者换句话说,我想使一个阵列的值成为关联数组 – LStarky

+0

'array_values的键()' - >'array_flip()' - >'array_intersect()' – Xorifelse

回答

0

好的,我有一个答案。也许有一种更快/更好的方式来做到这一点,并不涉及实际穿过阵列,但也许这是最好的方法。

$schema = array(); 
$rows = $pdo->query("DESCRIBE " . $table); 
// refactor array of associative arrays using column name as key 
foreach ($rows as $row) { 
    // pull off the first key-value which is the column name 
    $key = array_shift($row); 
    // add the rest of the array to $schema with the column name as the key 
    $schema[$key] = $row; 
}