【问题标题】:return multiple arrays from a query从查询中返回多个数组
【发布时间】:2010-08-14 17:56:11
【问题描述】:

我有两张桌子

名为services 的第一个表具有id_service、名称、日期。描述 名为services_images 的第二个表具有 id_img、img_name、id_service

现在假设我必须通过一个查询(如果可能)返回 2 个数组

第一个数组,其中包含来自表 "services" 的一个特定 ID 的字段 第二个数组,其中包含与表 "services_images" 中“服务”中所选 id 相关的所有图像的字段。

或者更好的是,只有一个数组具有与 1 中所述相同的数据,内部有一个名为“images”的数组,其中包含表 "services_images" 中列出的所有图像

我需要它来处理和显示 html 页面中的数据,这是唯一的方法。

如果我不能在 mysql 中做到这一点,我该如何在 PHP 中进行安排,我唯一能想到的就是 2 个查询

另外,我一直在努力提高自己的技能,因为我过去常常对所有内容进行一次查询,是否存在无法进行 1 次查询的情况? 谢谢!

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    编辑:我现在明白你的意思了——我第一次解释错了。

    执行此操作的唯一方法是执行多个查询。您必须执行以下操作:

    $sql = "SELECT * FROM services WHERE id_service=$id";
    $result = mysql_query($sql);
    $services = mysql_fetch_array($result);
    
    $new_sql = "SELECT * FROM services_images WHERE id_service=$id";
    $new_result = mysql_query($sql);
    while($row = mysql_fetch_array($result)){
         $serivices_images[] = $row;
    }
    

    其实我又改变主意了..试试这个:

    SELECT services.*,services_images.* FROM services, services_images WHERE services.id_service=services_images.id_service AND services.id_service=$id
    

    现在当您执行while($row = mysql_fetch_array($sql_query_result)) 时,您可能会返回所有行...但我不知道。只是猜测。

    【讨论】:

    • 我就是这么想的!谢谢大家!
    【解决方案2】:

    例如使用 PDO:

    $db = new PDO($dsn, $user, $pass);
    
    $sql = 'SELECT services.id_service, services.name, services.date, services.description, services_images.id_image, services_images.img_name
    FROM services, services_images
    WHERE services.id_service = services_images.id_service
    ORDER BY services.id_service';
    
    $services = array();
    
    foreach($db->query($sql) as $row)
    {
       $serviceId = $row['id_service'];
    
       if(!array_key_exists($serviceId, $services))
       {
          $services[$serviceId] = array(
              'name' => $row['name'],
              'date' => $row['date'],
              'description' => $row['description'],
              'services_images' => array()
          );
       }
    
       $imgId = $row['id_img'];
       $services[$serviceId]['services_images'][$imgId] => array(
          'id_image' => $imgId,
          'img_name' => $row['img_name']
       ); 
    }
    
    print_r($services);
    

    但请注意.. 如果您要加入的两个表(在本例中为 servicesservices_images)有任何同名的列,您将只能获得该行中最后一个检索到的值,除非您为它们设置别名或从您的选择语句中排除它们。

    此外,如果您的结果很大,您可能必须使用两个类似于 Thomas 建议的查询,因为您可能没有足够的内存来保存完整的数组结构。

    【讨论】:

    • 我还没有测试它,但它似乎只会给我第一个 id_image?对于我有超过 30 张图片的每个 service_id,我们需要另一个查询来循环结果。
    • No.. 只要这两个条目都存在,这将为您提供services_images 表中的每条记录,以及来自services 表的相关数据。在 sql 客户端中运行它,看看会发生什么:-)
    • 谢谢我现在知道了!那也没关系!然后在 PHP 中重新组织了 1 个查询
    猜你喜欢
    • 2015-10-29
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多