当为大数组使用for循环时PHP会冻结

时间:2015-03-03 17:47:42

标签: php mysql arrays for-loop freeze

尝试运行此脚本时遇到了一些麻烦:

<?php

$mysqli=new mysqli("localhost","root","mysqlpassword","MarcTextOldBib");
if (mysqli_connect_errno()) {echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$db_abfrage = "SELECT `cid` , `field_data` FROM T1xx" ;
$j=0;
$db_ausgabe = $mysqli->query($db_abfrage);
while($row = $db_ausgabe->fetch_object()){
    $names[$j] = array( "cid"           => $row->cid,
                        "field_data"    => $row->field_data,
                     );
    $j++;
}


$mysqli->close();

echo"
<table border='1'>
<thead><tr>
<th>ID</th> <th>Name</th>
</tr></thead>";

$ID=1;
$size = count($names);

for ( $i = 0; $i <= $size; $i++ ){
    $cid = $names[$i][cid];
    echo "<tr>";

    while( $ID != $names[$i][cid] ) {
        echo "<td>".($ID)."</td>";
        echo "<td></td>";
        echo "</tr>";
        $ID++;
    }

    if( ($ID) == $names[$i][cid] ) {
        echo "<td>" . ($ID) . "</td>";
        echo "<td>" . $names[$i][field_data] . "</td>";
        echo "</tr>";
        $ID++;
    }

}

echo "</table>";

?>

当我将for循环设置为“50”而不是count($ names)时,它就像魅力一样。但是当使用count($ names)时,我的电脑会完全冻结。 count($ names)是2788。

2 个答案:

答案 0 :(得分:2)

将“cid”放在引号中。

变化:

$names[$i][cid]

要:

$names[$i]['cid']

同样适用于

$names[$i]['fieldData']

答案 1 :(得分:1)

你有非常奇怪的代码,我已经简化了我的想法, 但是你在$ID++中试图得到的仍然是我的理解。

如果oyu解释我会为你解决剩下的问题:

<?php

$mysqli=new mysqli("localhost","root","mysqlpassword","MarcTextOldBib");
if (mysqli_connect_errno()) {echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$db_abfrage = "SELECT `cid` , `field_data` FROM T1xx" ;
$db_ausgabe = $mysqli->query($db_abfrage);
$names= array()
while($row = $db_ausgabe->fetch_assoc()){
    $names[] = $row
}


$mysqli->close();

echo"
<table border='1'>
<thead><tr>
<th>ID</th> <th>Name</th>
</tr></thead>";

$ID=1;

foreach ($names as $row ){
    $cid = $row['cid'];
    echo "<tr>";
    echo "<td>" . ($ID) . "</td>";
    echo "<td>" . ($ID != $row['cid'])?'':$row['field_data'] . "</td>";
    echo "</tr>";
    $ID++;


}

echo "</table>";

?>