简体   繁体   English

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

[英]Mapping SQL query results to JSON in PHP

I'm running into some issues getting the correct JSON output from my SQL query. 我在从SQL查询中获取正确的JSON输出时遇到了一些问题。 Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects. 本质上,我正在挣扎的是获取一组选项对象,而不是单个选项对象。

$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);

Gives me this output: 给我这个输出:

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

And here's what I'm trying to get to: 这就是我想要达到的目标:

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

I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know! 我想遵循最佳做法并适当地进行组织,如果有更好的方法可以解决此问题,请告诉我!

You need to store $attachment['matchupID'] as an array key of $data : 您需要将$attachment['matchupID']存储$attachment['matchupID'] $data的数组键:

$data = array();
while ($attachment = $db->fetch_array($attachments)){
    if (!isset($data[$attachment['matchupID']])) {
        $data[$attachment['matchupID']] = array (
            'id' => $attachment['matchupID'],
            'options' => array()
        );
    }
    $data[$attachment['matchupID']]['options'][] = array (
        "name" => $attachment['player_name'],
        "playerid" => $attachment['player_id']
    );
}

// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM