下面的脚本生成包含所需数据的txt文件,但它在文本文件中生成两次数据。
mysql_connect($hostname_MySQLCon, $username_MySQLCon, "") or die(mysql_error());
mysql_select_db($database_MySQLCon) or die(mysql_error());
$data = mysql_query("
SELECT sales_flat_order.increment_id, sales_flat_order.gift_message_id, sales_flat_order.status, gift_message.gift_message_id, gift_message.message
FROM sales_flat_order
JOIN gift_message ON sales_flat_order.gift_message_id = gift_message.gift_message_id
WHERE sales_flat_order.gift_message_id IS NOT NULL
GROUP BY sales_flat_order.increment_id
/* AND sales_flat_order.status = 'pending' */;")
or die(mysql_error());
while($result = mysql_fetch_array( $data ))
{
$dataRow[] = implode("|", $result);
}
$theFile = 'orders-meta.txt';
if (!$handle = fopen($theFile, 'a')) {
exit;}
if (fwrite($handle, implode("\r\n", $dataRow)) === FALSE) {
echo "Cannot write to file ($theFile)";
exit;}
echo "Success, the file was written.";
fclose($handle);txt文件中的示例输出:
100000001|100000001|1121|1121|pending|pending|1121|gift message|gift message
100000002|100000002|1123|1123|pending|pending|1123|Gift message|Gift message为什么它会为每个值生成两次?我如何才能将其更改为:
100000001|1121|pending|1121|gift message
100000002|1123|pending|1123|Gift message真的很感谢你的帮助。
谢谢
发布于 2012-10-04 19:07:56
从docs
返回与所读取的行相对应的字符串数组,如果没有更多的行,则返回FALSE。返回的数组类型取决于result_type的定义方式。通过使用MYSQL_BOTH (默认),您将获得一个同时具有关联索引和数字索引的数组。使用MYSQL_ASSOC,您只能获得关联索引(因为mysql_fetch_assoc()工作),使用MYSQL_NUM,您只能获得数字索引(因为mysql_fetch_row()工作)。
mysql_fetch_array获取每个结果两次,一次作为assoc数组,一次默认情况下作为数字索引数组。这就是为什么你会得到重复的行。
话虽如此,请不要使用mysql_*,因为它处于弃用过程中,请阅读文档页面上的阅读框,然后单击指向PDO或mysqli_*的链接,或链接here和here
发布于 2012-10-04 19:05:56
因为您使用的是mysql_fetch_array()而不是mysql_fetch_row()。
mysql_fetch_array的缺省$result_type为MYSQL_BOTH
资源数组mysql_fetch_array (
$result,int $result_type = MYSQL_BOTH )
这将产生如下的数组:
array(
0 => 100000001
'increment_id' => 100000001,
1 => 1121,
'gift_message_id' => 1121,
2 => 'pending',
'status' => 'pending',
3 => 1121,
4 => 'gift message',
'message' => 'gift message'
)为什么你要以如此低效的方式存储数据?为什么不这样做:
$theFile = 'orders-meta.txt';
if (!$handle = fopen($theFile, 'a')) {
exit;
}
while($result = mysql_fetch_array( $data )) {
fwrite($handle, implode("|", $result));
fwrite($handle, "\n\r");
}
fclose($handle);发布于 2012-10-04 19:05:53
默认情况下,mysql_fetch_array返回一个包含数字键和关联键的混合数组-因此每个值都是重复的。将获取行更改为:
mysql_fetch_array($data, MYSQL_ASSOC)https://stackoverflow.com/questions/12725845
复制相似问题