我有一个具有这种结构的数组:
$queues[n] Array (
[id] => integer
[idClient] => integer
[name] => string
[people] => integer )
其中填充了:
$query = "SELECT clients.idClient AS 'idClient', queues.idQueue AS 'idQueue', queues.name AS 'name' FROM clients, queues WHERE clients.idClient = queues.client";
$queues = null;
$result = mysql_query($query);
if ($result){
while ($queue = mysql_fetch_assoc($result)){
$queues[] = array ("idClient" => $queue['idClient'], "id" => $queue['idQueue'], "name" => $queue['name'], "people" => 0);
}
}
每个'n'值与来自数据库和人的队列匹配,默认情况下设置为0.
填充数组后,我再次使用每个队列查询数据库到其他表,以获取队列中的人数,并使用如下查询:
SELECT COUNT(*) FROM peoplequeued WHERE queue ='".$queue['name']."'
然后:
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
这里发生了一些奇怪的事情。如果我在foreach中回显$ queue ['people'],它会显示它得到的值,但是如果我在返回之前预览完整数组,它会回到0。
可能会发生什么?
答案 0 :(得分:4)
我的猜测是,您使用$queues
循环遍历foreach
,如下所示:
foreach ( $queues as $queue ) {
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
如果是,$queue
和$queues[$n]
之间没有“链接”,即修改$queue
,则不会修改$queues
。
如果是这种情况,您应该使用$queue
作为参考变量,或者修改$queues[$n]
并将$n
作为索引。
foreach ( $queues as &$queue ) { // add & so $queue is a reference to an element in $queues
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
unset($queue); // drop the reference, otherwise you might have unexpected results after modifying $queue outside the loop
......或......
foreach ( $queues as $n => $queue ) { // store index of "current" element in $n
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queues[$n]['people'] = $num_people[0]; // change $queue to $queues[$n]
}
}
或者,我建议您考虑将所有数据都放在一个语句中。看起来像这样的东西可能适合你:
select
baseTable.id,
baseTable.idClient,
baseTable.name,
peopleCount.count as people
from
baseTable
left join (
select
count(*) as count,
queue
from
peoplequeued
group by
queue
) as peopleCount on peopleCount.queue = baseTable.name
答案 1 :(得分:3)
听起来你可能正在使用foreach
循环遍历$queues
数组,如下所示:
foreach($queues as $queue) {
}
生成的每个$queue
变量都是一个副本,对它的更改不会保存到$queues
变量中。要按照您的意图保存更改,您需要执行以下操作:
foreach($queues as $k => $queue) {
$queue['people'] = 10;
$queues[$k] = $queue;
// or, more efficiently...
$queues[$k]['people'] = 10;
}
在PHP5中你也可以参考。见http://uk.php.net/manual/en/control-structures.foreach.php