Format JSON - PHP and MySql?

1

I need to mount a json as follows:

[
 {"SUPERMECADO 1": {"telefones": [ "1999999999","1999999991"]}  },
 {"SUPERMECADO 2": {"telefones": [ "1999999992","1999999993"]}  }
]

But currently my SQL is returning a array like this:

[
 {"campanha":"SUPERMECADO1","telefone":"1999999999"},
 {"campanha":"SUPERMECADO1", telefone":"1999999991"},
 {"campanha":"SUPERMECADO2", telefone":"1999999992"},
 {"campanha":"SUPERMECADO2", telefone":"1999999993"}
]

my code PHP :

$query = "SELECT campanha, telefone FROM rest";
$query = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
    $rows[] = $r;
}
echo json_encode($rows);

How can I set up my code PHP so that I can show all the phones by grouping the campaign names?

    
asked by anonymous 01.05.2017 / 16:24

1 answer

3

Try this in your code:

while($r = mysql_fetch_assoc($query)) 
{
    $rows[$r['campanha']]['telefones'][] = $r['telefone'];
}

Online Example IDEONE

    
01.05.2017 / 16:31