2016-12-29 62 views
0

我有一个PHP循环从我的表中获取数据并将其推入数组。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 = 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); 

我想添加其他键/值对称为points数组,并指定其为$total值。

我试过做$temp['points'] = $total,但它把它放在数组之外,而不是与外部循环数据。

这是函数的结果:

{ 
    "timestamp": 1482918104, 
    "children": [ 
     { 
      "id": "1", 
      "name": "Maya", 
      "age": "5", 
      "photoName": "maya.png", 
      "panelColor": "" 
     }, 
     { 
      "id": "2", 
      "name": "Brynlee", 
      "age": "3", 
      "photoName": "brynlee.png", 
      "panelColor": "green" 
     } 
    ] 
} 

我想告诉每一个这些儿童的点,但我不能确定如何将它添加到阵列的一部分。通过让所有孩子的收视率在一个查询

$child['points'] = $total; 
$temp[] = $child; 
+0

不要使用任何的'mysql_'功能。他们在几年前被弃用,并从PHP 7起正式删除。 –

+0

@AndyIbanez - 谢谢,我会研究这一点。 I – SBB

回答

3

你应该把它添加到$child变,只是增加该变量的$temp阵列之前。

事情是这样的:

$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) . ')'); 
} 
+0

grr,这么简单:/我一直试图将它添加到temp,没想到将它添加到子数组。将很快接受:) – SBB

+0

发生在每个人:)你有我的投票在那里保持问题清洁和明确! – Dekel

0

你也可以请求减少数据库: