PHP将数据添加到数组对象PHP

时间:2014-03-02 23:51:55

标签: php arrays

我试图将数据添加到下面的每个数组对象中。

[
       {
          "first_name":"Chris",
          "surname":"Mowbray",
          "id":"28"
       },
       {
          "first_name":"Gary",
          "surname":"Hume",
          "id":"29"
       },
       {
          "first_name":"Ian",
          "surname":"Hume",
          "id":"30"
       }
    ]

这是生成显示数组的php:

<?php
$selectedMatch = '( select max(event.match_id) from event)';
// need to update this match id based on usered slected on site
$getMatchPlayers = "select first_name,surname, id\n" . "from player, match_player\n" . "where player.id = match_player.player_id\n" . "and match_player.match_id = $selectedMatch";
$result = mysql_query($getMatchPlayers) or die(mysql_error());
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
    $temp[]    = $row;
    $player_id = $row['id'];
    $AppResult = mysql_query(getApps($player_id)) or die(mysql_error());
    $appearence = mysql_fetch_assoc($AppResult);
    // fb($temp);
}



header('Content-Type: application/json');
echo json_encode($temp);
exit;
function getApps($playerid){
    $getAppearances = "SELECT COUNT(player_id) \n" . "AS Appearances \n" . "FROM match_player\n" . "where player_id = $playerid\n";
    return $getAppearances;
}
?>

我试图在每个对象的'id'之后添加新数据,但我尝试过的所有内容都为数组添加了一个新索引。

$ appearence是我想要添加的内容

3 个答案:

答案 0 :(得分:1)

你试过这个吗?

 $temp['newKey'] = $appearence;  

答案 1 :(得分:1)

$ row ['appearance'] = $ appearance ['Appearance']并将$ temp [] = $ row指定为while()中的最后一个语句

答案 2 :(得分:0)

尝试添加包含结果merged数组 您已检索到所有必需信息。

while ($row = mysql_fetch_assoc($result)) {
    $player_id  = $row['id'];
    $AppResult  = mysql_query(getApps($player_id)) or die(mysql_error());
    $appearence = mysql_fetch_assoc($AppResult);
    $temp[]     = array_merge($row, $appearance);
}

在执行此操作时,请注意不要在$row$appearance中使用相同的数组键,假设您没有问题。