Npcink Blog
切换菜单

如何处理并拿到需要的 JSON 数据 - PHP

PHP 中关于数组和 JSON 间的处理

本页目录4 节

有时候,通过 PHP 的 get 或者 post 请求,得到的是 JSON 数据,我们该如何处理呢?

处理 JSON

  1. 使用 json_decode()函数解码
  2. 数组取值并输出
<?php
//生产JSON数据
$json_data = array ('id'=>1355471563,'name'=>"npc",'country'=>'usa',"office"=>array("microsoft",'oracle'=>'https://www.npc.ink/'));
$json_num = json_encode($json_data);
echo $json_num;
//拿到数据解码
$json_url=json_decode($json_num,true);
//取得需要的值
$one_data = $json_url['name'];
$two_data = $json_url['office']['0'];
$three_data = $json_url['office']['oracle'];
echo '<br />您本次的$one_data是:<br />'.$one_data."<br />";
echo '<br />您本次的$two_data是:<br />'.$two_data."<br />";
echo '<br />您本次的$three_data是:<br />'.$three_data."<br />";
?>

以上代码输出结果为:

{"id":1355471563,"name":"npc","country":"usa","office":{"0":"microsoft","oracle":"https://www.npc.ink/"}}
您本次的$one_data是:
npc
您本次的$two_data是:
microsoft
您本次的$three_data是:
https://www.npc.ink/

输出 JSON

<?php
header('Content-Type:application/json');//加上这行,前端那边就不需要var result = $.parseJSON(data);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

以上代码执行结果为:

{"a":1,"b":2,"c":3,"d":4,"e":5}

相关技术

参考文档