得到组合导致sql

时间:2013-02-24 20:35:19

标签: php sql

是否有可能从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
                )
        )

1 个答案:

答案 0 :(得分: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']);