如何使用 PHP 获取 JSON 格式


How can i get the JSON format using PHP

{  
   "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 )

请帮忙。提前感谢.....

简单尝试一下:

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

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

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

以下代码片段应完成示例中的工作:

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