数组占用太多内存

时间:2012-05-16 04:59:33

标签: php arrays memory

我正在创建一个数组来保存从查询返回的值 - 似乎添加到多维数组会导致脚本占用高达125Mb的内存并考虑到数组应该保留的数据总量不多超过5Mb,这很奇怪:

这是我正在做的事情:

try 
{
    if (!$link = mysql_connect(DB_Host, DB_User, DB_Password))
            Throw New Exception(mysql_error());
    if (!mysql_select_db("Spexplus_Demo"))
            throw New Exception(mysql_error());
} 
catch (Exception $e) 
{
    echo $e->getMessage().$e->getTraceAsString();
    exit(1);
}

$query = "select cda.categoryid as categoryId, 
                  cda.templatetype as templateType, 
                  hn.headerid as headerId, 
                  hn.name as headerName, 
                  an.attributeid as attributeId, 
                  an.name as attributeName
                  from categorydisplayattributes cda 
                  join categoryheader ch on cda.headerid = ch.headerid 
                  and cda.templatetype = ch.templatetype 
                  and cda.categoryid = ch.categoryid 
                  join headernames hn on cda.headerid = hn.headerid 
                  and hn.localeid = 1
                  join attributenames an on cda.attributeid = an.attributeid 
                  and an.localeid = 1";

$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))

        {
            $categorydisplayattributes[$row['categoryId']][$row['templateType']][$row['headerId']][$row['headerName']][$row['attributeId']][$row['attributeName']] =array() ;
        }


echo "Memory After CDA:".memory_get_usage(TRUE).Line_Terminator;
exit();

当我检查时,查询结果本身不会超过5Mb左右,但是,以这种方式将值分配给数组会导致峰值 - 有没有其他人遇到过这样的事情?

1 个答案:

答案 0 :(得分:2)

    while($row = mysql_fetch_assoc($result))


           {

//concatenate the values using '.' if string 

$index = $row['categoryId']][$row['templateType']][$row['headerId']][$row['headerName']][$row['attributeId']][$row['attributeName'];

                $categorydisplayattributes[$index] =array() ;
            }

试试看。