【问题标题】:MySQL schema into PHP associative arrayMySQL 模式转换为 PHP 关联数组
【发布时间】:2016-11-20 00:19:26
【问题描述】:

我确信这已经做过很多次了,但我很难找到简单的解决方案,可能是因为我很难把我的思想包起来。上下文是一个自定义 PDO 包装器。

总结:我想生成一个两级(?)数组schema,以便通过两种方式轻松访问 MySQL 表架构:

  1. 列类型/null/按列名的默认值(类似于 `schema['fieldname']['null'])。
  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');
  }
}

不要太拘泥于细节。基本上我想把一个平面数组变成同样的东西,但按列名分组。

【问题讨论】:

  • 或者换句话说,我想让一个数组的值成为关联数组的键
  • array_values() -> array_flip() -> array_intersect()

标签: php arrays pdo


【解决方案1】:

好的,我有一个答案。也许有一种更快/更好的方法来做到这一点,而不涉及实际遍历数组,但也许这是最好的方法。

$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;
}

【讨论】:

    猜你喜欢
    • 2011-05-08
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多