php - 如何仅获取第一个结果 mysql php - foreach 中的多个查询

标签 php mysql wordpress

我的 wordpress 数据库中有一个自定义表格。在数据库中,我展示了带有自己画廊 ID 的照片画廊。每个画廊都有多张照片,所以我可能有:

image_link: img1.png | upload_id: 47372
image_link: img2.png | upload_id: 47372
image_link: img3.png | upload_id: 47372
image_link: img4.png | upload_id: 373h3
image_link: img5.png | upload_id: 373h3

我有返回 img id 并将用户链接到他们可以查看图库的 URL 的代码:

          $results = $wpdb->get_results( "SELECT * FROM wp_prefix_photos WHERE user_email='" . $email . "' AND created_date > $sevenDays ORDER BY created_date ASC" );

          ob_start();
          $arr = array();
          foreach ( $results as $result )
          {
            $arr[] = "<div style='border: 1px solid black'><a href='https://mywebsite.com/?photoID=" . $result->upload_id . "'>https://mywebsite.com/?photoID=" . $result->upload_id . "</a></div>";

          }
          $unique_data = array_unique($arr);
          // now use foreach loop on unique data
          foreach($unique_data as $val)
          {
            echo $val;;
          }

          $output = ob_get_clean(); // set the buffer data to variable and clean the buffer
          return $output;

请注意,它被包裹在一个缓冲区中,因为它在 Wordpress 短代码中,并且 foreach 停止返回第一个结果。我还使用 array_unique() 来确保所有结果都是唯一的(不需要两次显示相同的 upload_id)。

现在,问题来了:我想为每个 upload_id 获取第一个且仅是第一个 image_link。当你坚持echo "<br>" . $result->image_link;里面foreach ( $results as $result ) ,它会打印每个与 id 匹配的 url,我不能使用 array_unique($arr);再次是因为每个 img url 都是唯一的。

我想我可以在 foreach($unique_data as $val) 中执行另一个数据库查询,使用 $val 作为 upload_id 并获取第一个结果,但是有什么方法可以调整它所以我不必这样做吗?如果我这样做,运行与 foreach 结果一样多的数据库查询是否会对服务器造成负担?

最佳答案

请将您的查询更改为

“SELECT max(image_link) as image_link,upload_id FROM wp_prefix_photos WHERE user_email='”。 $电子邮件。 "' AND created_date > $sevenDays group by upload_id ORDER BY created_date ASC"

关于php - 如何仅获取第一个结果 mysql php - foreach 中的多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53446807/

相关文章:

mysql - 当其他表格中有 PDF 时,如何选择不显示?

php - 如何通过在 wordpress 中获取帖子图像来更改宽度和高度?

Wordpress Multisite - 这是个好主意吗?

PHP 循环遍历 MySQL 函数返回的数组

php - 如何解决错误 : SQL authentication method unknown in Laravel-MySql

python - 从excel导入到mysql

php - Woocommerce archive-product.php 覆盖不适用于 underscores.me 主题

php - 如何从日期字段中仅选择月份?

php - 如果 id 存在则更新,否则插入 (ODBC)

mysql - 分组依据 - 需要单行显示