我如何json_encode
第一列名为id,其值为json对象,然后编码其余列,数据为子json对象?我的json是 有效
{
"id" :"1",
"first_name":"Henry",
"last_name" :"Lawrence",
"email" :"hlawrence0@storify.com",
"country" :"Italy",
"ip_address":"0.72.132.192"
}
我希望输出如下:
{
"id" :"1"{
"first_name":"Henry",
"last_name" :"Lawrence",
"email" :"hlawrence0@storify.com",
"country" :"Italy",
"ip_address":"0.72.132.192"
}}
{
"id" :"2"{
"first_name":"Bonny",
"last_name" :"Jackson",
"email" :"bjdsa0@storify.com",
"country" :"Italy",
"ip_address":"0.72.132.192"
}}
答案 0 :(得分:0)
你可以这样做:
$json = '{"id":"1","first_name":"Henry","last_name":"Lawrence","email":"hlawrence0@storify.com","country":"Italy","ip_address":"0.72.132.192"}';
$jsonEncode = json_decode($json, true);
$userArray[array_shift($jsonEncode)] = $jsonEncode;
$result = json_encode($userArray);
答案 1 :(得分:0)
试试这个:
<?php
$json = '[{
"id" :"1",
"first_name":"Henry",
"last_name" :"Lawrence",
"email" :"hlawrence0@storify.com",
"country" :"Italy",
"ip_address":"0.72.132.192"
},{
"id" :"2",
"first_name":"Dave",
"last_name" :"Chen",
"email" :"null@null",
"country" :"Canada",
"ip_address":"127.0.0.1"
},{
"id" :"4",
"first_name":"Foo",
"last_name" :"Bar",
"email" :"postmaster@localhost",
"country" :"US",
"ip_address":"0.0.0.0"
}]';
$json = json_decode($json, true);
array_walk($json, function(&$val) {
$tmp = $val;
$val = array('id' => $tmp['id']);
unset($tmp['id']);
$val['data'] = $tmp;
});
print_r($json);
Array
(
[0] => Array
(
[id] => 1
[data] => Array
(
[first_name] => Henry
[last_name] => Lawrence
[email] => hlawrence0@storify.com
[country] => Italy
[ip_address] => 0.72.132.192
)
)
[1] => Array
(
[id] => 2
[data] => Array
(
[first_name] => Dave
[last_name] => Chen
[email] => null@null
[country] => Canada
[ip_address] => 127.0.0.1
)
)
[2] => Array
(
[id] => 4
[data] => Array
(
[first_name] => Foo
[last_name] => Bar
[email] => postmaster@localhost
[country] => US
[ip_address] => 0.0.0.0
)
)
)