这是我的json:
{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}
我想使用PHP删除第二级密钥(例如"26:"
和"28":
)。
换句话说,我想用零索引数字键替换双引号码。
如何让它看起来像这样:
{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}
答案 0 :(得分:1)
这是demo。
代码:
// declare $json
$array=json_decode($json,true); // decode as array
// overwrite subarray with zero-indexed keys while preserving subarray values
$array['all_counts_reports']=array_values($array['all_counts_reports']);
var_export(json_encode($array)); // return to json
输入:
$json='{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}';
输出:
'{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}'
在您的javascript中,使用JSON.parse()
去除包装单引号:
var str='{"all_counts_reports":[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]}';
var json=JSON.parse(str);
console.log(json);
因为我们正在运行假设,如果你想删除all_counts_reports
键,你可以使用这个单行:
代码:
$new_json=json_encode(array_values(current(json_decode($json,true))));
输出:
'[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]'
答案 1 :(得分:0)
$array = json_decode($your_json_string,true);
print_r($array);
$result = array();
foreach($array['all_counts_reports'] as $rep){
$result['all_counts_reports'][] = array(
"name"=>$rep['name'],
"date"=>$rep['date'],
"trips_per_day"=>$rep['trips_per_day'],
"cash_trips"=>$rep['cash_trips'],
"credit_trips"=>$rep['credit_trips'],
"compliment_trips"=>$rep['compliment_trips'],
);
}
$result_json = json_encode($result);
echo $result_json;
可能有更好的解决方案,但现在就在我的脑海中
目前还不清楚你在寻找什么,如果你只想删除而不想保持原来的json那么你可以这样做。但是,如果您不希望将all_counts_reports
视为数组[]
,则此示例无效。
简单地传递给android然后上面就可以了。