在PHP中解析和构建JSON数组

   在PHP 5.2之后,PHP提供了对JSON数据的支持,分别是以下两个函数

   $json_obj = json_decode($json_str) #把JSON字符串数据解析成对象

   $json_str = json_encode($json_obj) #把对象转换成字符串

用过easyui同学可能都知道,easyui的datagrid接收是json的数据结构是这样的

{"total" : 2 , "rows" :
         [{"name" : "Herow","id": 123},
          {"name" : "happy" , "id" : 321}]
}

而php中用array("name" => "Herow")构建形成的JSON格式是都是包含在花括号{}中的,网上查了一下,找到了一种解决方法

解析JOSN
$json_str = '[{"name" : "Herow","id": 123},{"name" : "happy" , "id" : 321}]';
$json_obj = json_decode($json_str);
foreach($json_obj as $json_item){
     echo $json_item->name."+".$json_item->id;
}

构建JSON


#{"total" : 2 , "rows" : [{"name" : "Herow","id": 123},{"name" : "happy" , "id" : 321}]}
//json数组的key
$key= array("name", "id");
$rows = array();
     
$value1 = array("Herow",123);
//合并键值
$temp1 = array_combine($key, $value1);
//存入数组$rows中
array_push($rows,$temp1);
//以下都一样了,要构建多个数据用一个foreach就行了
$value2 = array("happy",321);
$temp2 = array_combine($key, $value2);
array_push($rows, $temp2);
     
$result = array(
     "total" => 2
     "rows" => $rows
);
echo json_encode($result);



Leave a Reply

Your email address will not be published. Required fields are marked *