dongzhuoxie1244 2016-11-20 00:19
浏览 23

MySQL模式转换为PHP关联数组

I'm sure this has been done before many times but I'm having trouble finding the simple solution, probably because it's hard for me to wrap my mind around it. The context is a custom PDO wrapper.

Summary: I want to produce a two-level (?) array schema to easily access a MySQL table schema in two ways:

  1. Column type/null/defaults by column name (something like `schema['fieldname']['null']).
  2. Array of fields (maybe produced by array_keys(schema)) to use with array_intersect to validate query fields.

Details:

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

Don't get too bogged down in the details. Basically I want to turn a flat array of arrays into the same thing but grouped by the column name.

  • 写回答

1条回答 默认 最新

  • douren2395 2016-11-20 01:50
    关注

    Okay, I have an answer. Maybe there's a faster/better way to do this that doesn't involve actually walking through the array, but maybe this is the best way.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题