我正在从 MySQL 中提取一些数据,然后我试图总结键相同的结果数组的值。我之前在这段代码中已经做到了这一点:
$q = "SELECT * FROM comenzi";
$result = $odb->query($q);
$sumArr = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ( !isset($sumArr[ $row['meniu_name'] ]) ) {
$sumArr[ $row['meniu_name'] ] = $row['meniu_name'];
}
$sumArr[ $row['meniu_name'] ] += $row['cantitate'];
}
arsort($sumArr);
$rowCount = 1;
echo "<table><tr id='tableHeader'><td>#</td><td>produs</td><td>cantitate</td></tr>";
foreach ($sumArr as $key => $value) {
echo "<tr><td>" . $rowCount . "</td><td>" . $key . "</td><td>" . $value . "</td></tr>";
$rowCount++;
}
echo "</table>";
这是我的工作示例,它使我们进入下一个有点相似的示例,但由于某种原因,它没有产生所需的结果:
$q = "SELECT * FROM comenzi";
$result = $odb->query($q);
$sumArr = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ( !isset($sumArr[ $row['utilizator'] ]) ) {
// $sumArr[ $row['utilizator'] ] = $row['utilizator'];
}
$sumArr[ $row['utilizator'] ] += $row['cantitate'];
}
arsort($sumArr);
print_r($sumArr);
$rowCount = 1;
echo "<table><tr id='tableHeader'><td>#</td><td>utilizator</td><td>cantitate produse</td></tr>";
foreach ($sumArr as $k => $v) {
$odb = new PDO("mysql:host=".$host.";dbname=".$db, $user, $pass);
$stmtCheck = $odb->prepare('SELECT nume, prenume, email, telefon FROM utilizatori WHERE id=?');
$stmtCheck->execute(array($k));
$r = $stmtCheck->fetch();
echo "<tr><td>" . $rowCount . "</td><td>" . "<b>nume: </b>" . $r[0] . "<b> prenume: </b>" . $r[1] . "<b> email: </b>" . $r[2] . "<b> telefon: </b>" . $r[3] . "</td><td>" . $v . "</td></tr>";
$rowCount++;
}
echo "</table>";
这里发生的事情非常可疑:注释行// $sumArr[ $row['utilizator'] ] = $row['utilizator'];
,如果将其注释掉,我会得到预期的结果,但是将其注释掉我会得到错误:
注意:未定义的偏移量
如果我不评论该行,我不会得到未定义的偏移错误,但我的值是荒谬的。
正确值:Array ( [22] => 19 [32] => 11 )
未注释掉该行的值:Array ( [32] => 43 [22] => 41 )
我什至无法理解它获得这些值的数学方式,找不到任何可以让我找到正确方向的东西,因此我很困惑。