Format JSON - PHP and Mysql?

Asked

Viewed 211 times

1

I need to ride a json as follows:

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

But currently my SQL is returning a array thus:

[
 {"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 build my code PHP so that I show all phones grouping campaign names?

1 answer

3


Try it like this in your code:

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

Online Example IDEONE

  • 1

    thank you @Virgilio worked, I will put your answer as correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.