0

I'm running into some issues getting the correct JSON output from my SQL query. 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!

1
  • Will the id be same for all your rows ? Commented Jul 9, 2017 at 16:44

1 Answer 1

1

You need to store $attachment['matchupID'] as an array key of $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);
Sign up to request clarification or add additional context in comments.

1 Comment

The solution is always so damn simple! Thank you my friend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.