如何使用PHP获取JSON格式

时间:2016-04-27 13:55:26

标签: php json

{  
   "apple":[  
      "get",
      "get me an apple"
   ],
   "orange":[  
      "get me one",
      "get some"
   ],
   "banana ":[  
      "cut them all",
      "get them"
   ],

}

我如何获得格式?我使用print_r($ sql)打印短语和动作列时的SQL输出;是 Array ( [phrases] => get [actions] => apple ) Array ( [phrases] => get me an apple [actions] => apple ) Array ( [phrases] => Get me one [actions] => orange ) Array ( [phrases] => Get some [actions] => orange ) Array ( [phrases] => cut them all [actions] => Banana ) Array ( [phrases] => get them [actions] => Banana )

请帮忙。谢谢!

2 个答案:

答案 0 :(得分:7)

试一试:

$tempArray = array();
while($rec = mysql_fetch_assoc($sql)){
    $tempArray[$rec['actions']][] = $rec['phrases'];
}
echo json_encode($tempArray);

答案 1 :(得分:0)

存储在$sql变量中的内容属于数据类型array。要将数组转换为各自的json字符串表示形式,您需要对其进行编码。

标准PHP lib通过json_encode提供此功能。

以下代码段应该在您的示例中完成:

$tmp = [];
foreach ($sql as $row) {
    $response[$row['actions']][] = $row['phrases'];
}
$json = json_encode($tmp);