在SQL中将SQL查询结果映射到JSON

时间:2017-07-09 16:40:30

标签: php mysql json

我遇到了一些从SQL查询中获取正确JSON输出的问题。基本上我正在努力的是获得一个选项对象数组而不是单个选项对象。

$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup 
        INNER JOIN matchup_option
        ON matchup_option.matchupID= matchup.matchupID;';

$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
    $data[] = array (
        'id' => $attachment['matchupID'],
        'options' => array(
            array (
                "name" => $attachment['player_name'],
                "playerid" => $attachment['player_id']
            )
        )
    );
    //VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);

给我这个输出:

{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        }
     ]
  },
  {
     "id":"111222",
     "options":[
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}

这就是我想要达到的目标:

{
"matchup":[
  {
     "id":"111222",
     "options":[
        {
           "name":"111",
           "playerid":"111"
        },
        {
           "name":"222",
           "playerid":"222"
        }
     ]
  }
]
}

我想遵循最佳做法以及适当的结构,如果有更好的方法,请告诉我!

1 个答案:

答案 0 :(得分:1)

您需要将extension UIColor { static var myRed: UIColor { return UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0) } static var myBlue: UIColor { return UIColor(red: 0.08, green: 0.49, blue: 0.49, alpha:1.0) } } 存储为$attachment['matchupID']的数组键:

$data