如何使用foreach循环从表中获取数据
问题描述:
我想从表中获取数据到数组中,并且我不想使用foreach循环来处理速度问题。如何使用foreach循环从表中获取数据
我尝试使用
function getRowsAssoc()
{
$ret = array();
while (($temp = mysql_fetch_assoc($this->result)) !== FALSE)
{
if (count($temp) > 0)
{
$ret[] = $temp;
}
}
if (count($ret) > 0)
{
return $ret;
}
else
{
return FALSE;
}
}
然而,这导致对。
Array (
[0] => Array ([MySKU] => BB1-3500-48 [UPC] => 721343100171)
[1] => Array ([MySKU] => BC7-3501-19 [UPC] => 721343103516)
[2] => Array ([MySKU] => BC7-3501-95 [UPC] => 721343103523)
[3] => Array ([MySKU] => BB1-3502-12 [UPC] => 721343114000)
[4] => Array ([MySKU] => bc7-2370-03 [UPC] => 721343121602)
)
这个问题是不是返回副教授阵列它添加在它的上面有编号数组所以现在我无法从该项目代码的数据。
我想获得这样的
Array (
[MySKU] => BB1-3500-48 [UPC] => 721343100171
[MySKU] => BC7-3501-19 [UPC] => 721343103516
[MySKU] => BC7-3501-95 [UPC] => 721343103523
[MySKU] => BB1-3502-12 [UPC] => 721343114000
[MySKU] => bc7-2370-03 [UPC] => 721343121602
)
答
指定密钥:
所有你应该知道的function getRowsAssoc()
{
$ret = array();
while (($temp = mysql_fetch_assoc($this->result)) !== FALSE)
{
if (count($temp) > 0)
{
$ret[$temp["MySKU"]] = $temp;
}
}
if (count($ret) > 0)
{
return $ret;
}
else
{
return FALSE;
}
}
+0
这工作!谢谢 – MarkGreen 2013-05-09 14:37:42
答
首先,如何结果阵列的结构应该。
对于结构类似
Array
(
[MySKU-x] => UPC-x
[MySKU-y] => UPC-y
[MySKU-z] => UPC-z
)
您可以使用此:
function getRowsAssoc()
{
$return = array();
while (($temp = mysql_fetch_assoc($this->result)) !== false)
{
if (count($temp) > 0)
{
$return[$temp['MySKU']] = $temp['UPC'];
}
}
if (count($return) > 0)
{
return $return;
}
else
{
return false;
}
}
注:使用库MySQLi或PDO,而不是MySQL的(弃用的5.5)。 – Aleph 2013-05-09 13:51:58
“对于速度问题”...我不认为在foreach和while或者之间有任何速度差异,至少有一个人类可以察觉的速度问题 – aleation 2013-05-09 13:56:39
'foreach'用于迭代现有数组。在这种情况下,你正在用'while'构建数组。你不能用'foreach'替换它,因为没有你可以使用它的数组。 – Lukas 2013-05-09 14:01:39