【问题标题】:Retrieve database table names and print them out检索数据库表名并打印出来
【发布时间】:2023-03-26 11:32:01
【问题描述】:

这应该相当简单。我制作了一个 SQL 查询,它将所有匹配的数据库表名转储到一个数组中。我想把它们打印出来,但由于某种原因我不能。请帮忙!

数据库表命名为:example_1、example_2等

我的代码:

$sql = "SHOW TABLES LIKE 'example_%'";
$results = $wpdb->get_results($sql);

执行 print_r($results) 显示所有表名都已成功检索。 示例输出:

Array ( [0] => stdClass Object ( [Tables_in_wordpress (example_%)] => example_1 ) [1] => stdClass Object ( [Tables_in_wordpress (example_%)] => example_2 ) )

然后我尝试了:

foreach($results as $res) {
  echo $res;
}

但没有运气。如何遍历$results 以打印出每个表名?有没有像 $results[0].value 这样的东西可以用来检索值?

【问题讨论】:

    标签: php arrays database wordpress


    【解决方案1】:

    我相信这是你需要做的:

    $sql = "SHOW TABLES LIKE '%'";
    $results = $wpdb->get_results($sql);
    
    foreach($results as $index => $value) {
        foreach($value as $tableName) {
            echo $tableName . '<br />';
        }
    }
    

    => 将键和值从多维数组中分离出来。

    【讨论】:

    • 是的,做到了!你就是那个男人。非常感谢......刚刚学到了一些新东西。
    【解决方案2】:

    试试下面的代码。

    global $wpdb;
    $res = $wpdb->tables();
    var_dump($res); 
    

    【讨论】:

    • 这是在WordPress中获取表格列表的正确方法。
    • 这仅提供 WordPress 默认表,而不是插件或主题添加的自定义表 @Mybbor 是从 DB 获取所有表名的正确方法
    【解决方案3】:

    这可以使用array_column 来简化。

    $tables = array_column( $wpdb->get_results("show tables"), "Tables_in_local" );
    
    foreach( $tables as $table ) {
        echo $table;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多