gpt4 book ai didi

php - 缓存并迭代关联数组的数组

转载 作者:行者123 更新时间:2023-11-29 09:01:01 25 4
gpt4 key购买 nike

我想缓存我的 mysql 结果以减少数据库负载。为了缓存结果,我使用以下函数:

$cached = $this->getMemCacheX($name);

if ($cached === false)
{
$res = mysql_query($query, $con) or die(mysql_error());
if ($res === false) exit('Database failure.');
if ($fetch === "assoc")
{
$data = mysql_fetch_assoc($res);
}
else if ($fetch === "array")
{
$data = mysql_fetch_array($res);
}
if (mysql_num_rows($res) === 0) $data = 0;
$cr = $this->saveMemCacheX($name, $data);
if ($cr === false) exit('Cache failure.');
return $data;
}
else
{
return $cached;
}

我的问题是我需要保存并加载一个结果集,我曾经使用 while(mysql_fetch_assoc())-Loop 进行迭代,如下所示:

$res = mysql_query("...");
while ($data = mysql_fetch_assoc($res))
{
...
}

现在我需要将结果存储在缓存中,但因为我无法存储 $res,所以我需要先获取结果。

如何迭代已经获取的结果集?我尝试了一些 foreach 循环但没有找到解决方案。

我应该如何获取结果以便从数据库结果中获取关联数组的数组?

最佳答案

mysql_fetch_* 函数一次获取一行数据。它们不返回整个结果集。为此,您必须循环结果集并构建自己的数组:

$data = array();
while($row = mysql_fetch_assoc($result)) { // fetch as an associative array
$data[] = $row;
}

关于php - 缓存并迭代关联数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8622190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com