Mysql数据只将最后的结果拉入Json数组

时间:2016-04-03 23:59:55

标签: php mysql json

我从表中拉出多行并将它们格式化为此标准:3把剑,5把匕首等等。

那么当我尝试将这些数据放入json数组时,它只会将最后一个结果拉为[{"weapons":"You Used: 3 Rusty Dagger's, "}]它应该说:[{"weapons":"You Used: 3 Rusty Dagger's, 2 Swords"}]

这是我目前正在使用的查询,它将在while循环中完美显示:

$get_weapons = mysql_query("SELECT 
   O.player_id,
   O.item_id,
   O.name,
   O.attack,
   O.defense,
   O.type,
   O.owned,
   (SELECT 
      sum(owned) FROM items_owned 
    WHERE owned <= O.owned AND player_id=$id) 'RunningTotal' 
FROM items_owned O
HAVING RunningTotal <= $mob_avail 
ORDER BY attack DESC");
// Get Weapon Info
while($weapon = mysql_fetch_array($get_weapons)){
    $weapon_id = $weapon['item_id'];
    $weapon_name = $weapon['name'];
    $weapon_attack = $weapon['attack'];
    $weapon_defense = $weapon['defense'];
    $weapon_owned = $weapon['owned'];
    // Formatting Weapons Message
    $weapon_message = 'You Used: '.$weapon_owned.' '.$weapon_name.'\'s, ';
}
$data[] = array('weapons'=>$weapon_message);
echo json_encode($data);

我知道$data数组不在while循环中,但我只需要一个数组,所以我有点坚持要解决这个问题问题。任何帮助都很棒

1 个答案:

答案 0 :(得分:0)

在将结果附加到消息之前,您应该添加一个静态变量。
以下是参考答案:

 $get_weapons = mysql_query("SELECT O.player_id, O.item_id, O.name, O.attack, O.defense, O.type, O.owned, (
        SELECT sum(owned) FROM items_owned WHERE owned <= O.owned AND player_id=$id) 'RunningTotal' FROM items_owned O HAVING RunningTotal <= $mob_avail ORDER BY attack DESC");
        // Initialize the message
        $weapon_message = 'You Used: ';
        // Get Weapon Info
        while($weapon = mysql_fetch_array($get_weapons)){
            $weapon_id = $weapon['item_id'];
            $weapon_name = $weapon['name'];
            $weapon_attack = $weapon['attack'];
            $weapon_defense = $weapon['defense'];
            $weapon_owned = $weapon['owned'];
            // Formatting Weapons Message
            $weapon_message = $weapon_message.$weapon_owned.' '.$weapon_name.'\'s, ';
        }
        $data[] = array('weapons'=>$weapon_message);
        echo json_encode($data);