0

是否有可能从 2 个表productsproducts image关系表中得到这样的结果......

我正在使用 php。我可以用 php 组织数据,但由于性能原因,我想使用 sql 以这种形式获取数据。我知道 sql 连接,但它提供了简单的数组数据。我需要数据作为数组中的数组。

Products桌子:

id   name     
1    product1        
2    product2

images桌子:

product_id  imageid
1           1
1           2
1           3
2           4
2           5
2           6


[0] => Array
        (
            [id] => 1
            [images] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

        )
[1] => Array
        (
            [id] => 2
            [images] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )
        )
4

1 回答 1

0

不,不可能直接从关系 (SQL) 数据库中获取数组中的数组作为结果。

您需要遍历结果并自己创建数组,例如

$productsById = array();

foreach ($dbRows as $row) {
    if (!isset( $productsById[$row['product_id']] )) {
        $product = array(
            'id' => $row['product_id'],
            'name' => $row['product_name']
        );
        //note the use of the & to set the $product array by reference
        $productsById[$row['product_id']] = &$product;
    }
    //note the use of the & to retrieve the $product array by reference
    else $product = &$productsById[$row['product_id']];

    $product['images'][] = array(
        'id' => $row['image_id']
    );

    //We unset this because we accessed it by reference above; this prevents referencing the wrong product
    //on the next iteration of the loop.
    unset($product);
}

或者,要获取对象数组:

$productsById = array();

foreach ($dbRows as $row) {
    if (!isset( $productsById[$row['product_id']] )) {
        $product = new stdClass;
        $product->id = $row['product_id'];
        $product->name = $row['product_name'];
        $product->images = array();
        $productsById[$row['product_id']] = $product;
    }
    else $product = $productsById[$row['product_id']];

    $image = new stdClass;
    $image->id = $row['image_id'];
    $product->images[] = $image;
}

但是,还值得一提的是,如果您使用的是 MySQL(并且数据库可移植性不是问题),您可以使用 GROUP_CONCAT 函数,例如:

SELECT p.id as product_id, p.name as product_name, GROUP_CONCAT(i.id) as image_ids
FROM product p
LEFT JOIN image i ON p.id = i.product_id
GROUP BY p.id

然后在您的 PHP 中,每个产品只有一个 $row 数组,您可以简单地使用以下命令获取图像 ID:

$imageIds = explode(',', $row['image_ids']);
于 2013-02-25T01:53:16.427 回答