PHP推入数组
我有一个PHP循环,它从我的表中获取数据并将其推送到数组中PHP推入数组,php,arrays,Php,Arrays,我有一个PHP循环,它从我的表中获取数据并将其推送到数组中 $children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c"); $temp = array(); while ($child = mysql_fetch_assoc($children)) { // Get the child's reatings $ratings = mysq
$children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c");
$temp = array();
while ($child = mysql_fetch_assoc($children)) {
// Get the child's reatings
$ratings = mysql_query('
SELECT r.behaviourID, t.points, t.typeName
FROM behaviourRatings as r
JOIN behaviourTypes as t
ON r.behaviourID = t.typeID
WHERE r.childID = ' . $child['id']);
// Loop over the ratings
$totalPoints = 0;
while ($childRatings = mysql_fetch_array($ratings)){
$totalPoints = ($totalPoints + $childRatings['points']);
}
// We can only max out at our set max
if(($totalPoints + $maxPoints) > $maxPoints) {
$total = $maxPoints;
} else if($totalPoints < 0){
$total = ($maxPoints + $totalPoints);
}else{
$total = ($maxPoints - $totalPoints);
}
// Set the child array
$temp[] = $child;
}
$response = array();
$response['timestamp'] = $currentmodif;
$response['children'] = $temp;
echo json_encode($response, JSON_PRETTY_PRINT);
我想显示每个子项的点,但我不确定如何将其添加到数组的该部分。您应该将其添加到
$child
变量中,然后再将该变量添加到$temp
数组中:
$child['points'] = $total;
$temp[] = $child;
在将该变量添加到
$temp
数组之前,应将其添加到$child
变量中:
$child['points'] = $total;
$temp[] = $child;
您还可以通过在一个查询中获得所有子级的评级来减少对数据库的请求 大概是这样的:
$children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c");
$childrenIds = [];
while ($child = mysql_fetch_assoc($children)) {
$childrenIds[] = $child['id'];
}
if (!empty($childrenIds)) {
$ratings = mysql_query('
SELECT r.behaviourID, t.points, t.typeName
FROM behaviourRatings as r
JOIN behaviourTypes as t
ON r.behaviourID = t.typeID
WHERE r.childID IN (' . implode(',', $childrenIds) . ')');
}
您还可以通过在一个查询中获得所有子级的评级来减少对数据库的请求 大概是这样的:
$children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c");
$childrenIds = [];
while ($child = mysql_fetch_assoc($children)) {
$childrenIds[] = $child['id'];
}
if (!empty($childrenIds)) {
$ratings = mysql_query('
SELECT r.behaviourID, t.points, t.typeName
FROM behaviourRatings as r
JOIN behaviourTypes as t
ON r.behaviourID = t.typeID
WHERE r.childID IN (' . implode(',', $childrenIds) . ')');
}
grr,很简单:/I我一直试图将其添加到temp,但没有想到将其添加到子数组。很快就会接受:)发生在每个人身上:)你得到了我的选票,让问题变得清晰明了!grr,很简单:/I我一直试图将其添加到temp,但没有想到将其添加到子数组。很快就会接受:)发生在每个人身上:)你得到了我的选票,让问题变得清晰明了!不要使用任何
mysql\u
函数。它们在几年前就被弃用了,从PHP7开始就被正式删除了。@AndyIbanez-谢谢,我将对此进行研究。我不使用任何mysql\uuz
函数。它们在几年前就被弃用了,从PHP7开始就被正式删除了。@AndyIbanez-谢谢,我将对此进行研究。我