这实质上非常简单,我刚刚对它进行了相当详细的介绍。我的数据结构如我的帖子底部所示。我的目标是以简单的电子表格格式组织数据,“平整”关系数据库。例如:简单的关系型数据库 - 高效的查询
Product1 URL
Product2 URL URL URL
Product3 URL
我的初始方法如下。我寻找替代品的原因是我在产品表中有> 10,000行,每个产品平均有5个网址。这会产生大量的MySQL查询(实际上超出了我的共享托管资源),必须有更好的方式,对吧?我的代码已被简化以提炼我的问题的本质。
我的做法
//Query to get all products
$products = mysql_query("SELECT * FROM products");
$i = 0;
//Iterate through all products
while($product = mysql_fetch_array($products)){
$prods[$i]['name'] = $product['name'];
$prods[$i]['id'] = $product['id'];
//Query to get all URLs associated with this particular product
$getUrls = mysql_query("SELECT * FROM urls WHERE product_id =".$product['id']);
$n = 0;
while($url = mysql_fetch_array($getUrls)){
$prods[$i]['urls'][$n] = $url['url'];
}
}
结果
需要明确的是,这是预期的结果,产量预期。我只需要一种从原始数据库表格到这个多维数组的更有效的方式。我怀疑有更有效的查询数据库的方法。另外,据我所知,这个数组在扩展到所需大小时使用了大量内存。因为我的目标是使用这个数组将数据导出到.csv,所以如果效率更高,我会考虑使用XML(或其他)作为中介。因此,请随时提出完全不同的方法。
//The result from print_r($prods);
Array
(
[0] => Array
(
[name] => Swarovski Bracelet
[id] => 1
[urls] => Array
(
[0] => http://foo-example-url.com/index.php?id=7327
)
)
[1] => Array
(
[name] => The Stranger - Albert Camus
[id] => 2
[urls] => Array
(
[0] => http://bar-example-url.com/index.php?id=9827
[1] => http://foo-foo-example-url.com/index.php?id=2317
[2] => http://baz-example-url.com/index.php?id=5644
)
)
)
我的数据库架构
产品
id product_name
1 Swarovski Bracelet
2 The Stranger - Albert Camus
3 Finnegans Wake - James Joyce
网址
id product_id url price
1 1 http://foo-example-url.com/index.php?id=7327 £16.95
2 2 http://bar-example-url.com/index.php?id=9827 £7.95
3 2 http://foo-foo-example-url.com/index.php?id=2317 £7.99
4 2 http://baz-example-url.com/index.php?id=5644 £6.00
5 3 http://bar-baz-example-url.com/index.php?id=9534 £11.50
URLs.product_id链接products.id
如果你已经阅读过这篇文章,非常感谢你的耐心!我期待着阅读你的回复。那我该如何正确地做到这一点?
你打算如何来表示CSV两个层次结构? –
@Marcelo Cantos:OP告诉我们,每个产品最多可以有五个URL;无论如何,他可以保存到csv'product; url 1; ...; url n'中,然后在检索该文件时读取产品,然后一次一个地址,直到行的末尾 – Marco
最左列中的产品,根据需要列出右侧的URL。电子表格中会有空格。 – IsisCode