2016-12-29 66 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

你也可以請求減少數據庫: