0

这是我的mysql脚本

$result = mysql_query("SELECT users.*,games.game_names,games.id AS games_id
FROM users
LEFT JOIN games ON FIND_IN_SET(games.id,users.games)") or die(mysql_error());   
while($user = mysql_fetch_array($result, MYSQL_ASSOC)) {        
    $array = $user['games'];
    $name   =   $user['game_names'];
    $pieces = explode(",", $name);          
    $users[] = array(
                'users'=>array(
                    'id' => $user['id'],
                    'user' => $user['user'],
                    'games' =>  $pieces
                )
    );      

}   
$output = json_encode(array('statics' => $users));
echo $output;

我有 2 个用户。user1 有 4 个游戏。User2 有 3 个游戏。

我正进入(状态

{
statics: [
    {
        users: {
            id: "1",
            user: "user1",
            games: [
                "football"
            ]
        }
    },
    {
        users: {
            id: "1",
            user: "user1",
            games: [
                "cricket"
            ]
        }
    },
    {
    users: {
        id: "1",
            user: "user1",
            games: [
                "athletics"
            ]
        }
    },
    {
        users: {
            id: "1",
            user: "user1",
            games: [
                "badminton"
            ]
        }
    },
    {
        users: {
            id: "2",
            user: "user2",
            games: [
                "athletics"
            ]
        }
    },
        {
        users: {
            id: "2",
            user: "user2",
            games: [
                "badminton"
            ]
        }
    },
    {
        users: {
            id: "2",
            user: "user2",
            games: [
                "basketball"
            ]
        }
    }
]
}

但我必须按以下格式排序和需要

    {
statics: [
    {
        users: {
            id: "1",
            user: "user1",
            games: [
                "football",
                "cricket",
                "athletics",
                "badminton"
            ]
        }
    },        
    {
        users: {
            id: "2",
            user: "user2",
            games: [
                "athletics",
                "badminton",
                "basketball"
            ]
        }
    }

]
}

我应该如何准备我的查询以获得这个结果?

4

1 回答 1

0

试试这个代码:

$result = mysql_query("SELECT users.*,games.game_names,games.id AS games_id
FROM users
LEFT JOIN games ON FIND_IN_SET(games.id,users.games)") or die(mysql_error());   
$result_array=array();
while($user = mysql_fetch_array($result, MYSQL_ASSOC)) {        
    $name   = $user['game_names'];
    $pieces = explode(",", $name);
    array_push($result_array, array(
        'users'=>array(
            'id' => $user['id'],
            'user' => $user['user'],
            'games' =>  $pieces
        )
    ));
}   
$output = json_encode(array('statics' => $result_array));
echo $output;
于 2014-03-21T13:40:13.163 回答