简体   繁体   English

格式化 $wpdb->get_results

[英]Formatting $wpdb->get_results

I used ...我用了 ...

$result = $wpdb->get_results( $query );
foreach ( $result as $print ) {
    echo $print->name;
    echo $print->count;
    echo "<br>";
}

output is:输出是:

jo2 
clea10
jim10

Now I somehow need to make it like现在我不知何故需要让它像

  ['jo', '2'],
  ['clea', '10'],
  ['jim', '10'], 

I tried我试过了

<?php
     foreach ( $result as $print ) {
         echo "['".$print->name."', '".$print->count."'],";
     }
 ?>

And并且

if($result->num_rows > 0){
      while($row = $result->fetch_assoc()){
          echo "['".$row['name']."', ".$row['count']."],";
      }
}

But it does not work.但它不起作用。 I'm trying to run this inside Wordpress using wordpressDatabase that is why I used $wpdb->get_results我正在尝试使用 wordpressDatabase 在 Wordpress 中运行它,这就是我使用$wpdb->get_results

I am not sure what you were querying so I mocked up another example to just return the pages of the site.我不确定你在查询什么,所以我模拟了另一个例子来返回网站的页面。 You can substitute post_name for name and count for ID in your example.您可以在示例中用 post_name 代替 name 并用 count 代替 ID。

I just added spaces to your attempt to match WP Standards a little closer but working with quotations is never that readable.我只是在您尝试更接近 WP 标准的尝试中添加了空格,但使用引号从来没有那么可读。

$result = $wpdb->get_results ( "
                SELECT *
                FROM  $wpdb->posts
                    WHERE post_type = 'page'
            " );

foreach ( $result as $key => $print ) {
  echo "['" . $print->post_name . "', '" . $print->ID . "'],<br>";
}

Another approach, if you are comfortable reading it this way, is to use double quotes around the entire output.另一种方法是在整个输出周围使用双引号,如果您愿意以这种方式阅读它的话。

foreach ( $result as $key => $print ) {
  echo "['{$print->post_name}', '{$print->ID}'],<br>";
}

If neither approach is working I'd suggest you may have an issue with your query in general but it is hard to say without more inforamtion如果这两种方法都不起作用,我建议您总体上可能对您的查询有疑问,但如果没有更多信息就很难说

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM