2016-12-29 7 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" 
     } 
    ] 
} 

は、私が子どもたちのそれぞれのポイントを表示したいが、私は、アレイの一部に追加する方法がわからないと思います。

+0

'mysql_'関数のいずれかを使用しないでください。それらは数年前に廃止され、PHP 7以降正式に削除されました。 –

+0

@AndyIbanez - ありがとう、私はこれを調べます。私は – SBB

答えて

3

あなただけ$temp配列への変数のことを追加する前に、$child変数に追加する必要があります。

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

grrなので、単純です:/私はそれをtempに追加しようとしていましたが、それを子配列に追加することは考えていませんでした。まもなく受け入れます:) – SBB

+0

皆に起こります:)あなたは質問をきれいにしてクリアに保つためにそこに投票しました! – Dekel

0

はまた、あなたは1つのクエリですべての子の格付けを取得することにより、データベースへの要求を減らすことができます。このような

何か:

$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) . ')'); 
} 
関連する問題