[英]Converting a JSON string to a JSON array
我有这样的CSV文件
first_name,last_name,phone
Joseph,Dean,2025550194
Elbert,Valdez,2025550148
使用来自GitHub的csv-to-json.php我得到这样的输出
[{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}]
这几乎是我想要的-但是不是
"phone": "2025550194"
我需要
"phone": [{
"type": "phone",
"number": "2025550194"
}]
我该如何纠正?
如果您获得JSON字符串,那么您当然会首先将其转换为以下数组:
$arr = json_decode($json, true);
但是可能您已经有了该数组。 然后将以下循环应用于它:
foreach($arr as &$row) {
if (isset($row['phone'])) { // only when there is a phone number:
$row['phone'] = [[ "type" => "phone", "number" => $row['phone'] ]];
}
}
看到它在eval.in上运行。
您可以使用以下命令将csv-to-json.php代码更改为您想要的输出:-
选项1 :-
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
if ($j == 'phone') {
$newArray[$j] = array('type' => $j, 'number' => $d);
} else {
$newArray[$j] = $d;
}
}
选项2:-
$json_response = [{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}];
$result = json_decode($json_response);
$final_result = array();
foreach ($result as $row) {
$row['phone'] = array('type' => 'phone', 'number' => $row['phone']);
$final_result[] = $row;
}
echo json_encode($final_result);
它可能会帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.