php - 在 PHP,Drupal 8 中将 CSV 转换为嵌套的 JSON 对象
问题描述
我正在尝试将 CSV 转换为由文件中每一行的嵌套数组组成的 JSON 对象。
我尝试了一些类似的 SO 问题,但还没有找到完全正确的解决方案。
我正在尝试根据 CSV 每一行中的第一个值来设置一个带有少量嵌套对象的 JSON 对象。
我的 CSV 文件,标题为 data_source.csv,如下所示:
Organisation ID,Organisation Name,Postcode,Industry
111,Organisation A,SW2 4DL,School
123,Organisation B,S2 5PS,School
234,Organisation C,EC2 3AD,School
...there are several more rows
我的 PHP 代码(在 Drupal 8 的控制器中):
namespace Drupal\webform_autocomplete_csv\Controller;
use Drupal\Core\Controller\ControllerBase;
class WebformAutocompleteCsvController extends ControllerBase {
public function content() {
//make sure file can be accessed
if (($handle = fopen('sites/default/files/data_source.csv', 'r')) === false) {
die('Error opening file');
}
$organisation_id = fgetcsv($handle);
//take the first value on each row
array_shift($organisation_id);
//create an array
$data = array();
while ($row = fgetcsv($handle)) {
$key = array_shift($row);
$data[$key] = array_combine($organisation_id, $row);
}
$json_object = json_encode($data);
return $json_object;
} //close content()
}
理想的情况是具有一系列嵌套对象的单个 JSON 对象,例如:
Object {
111 {
Organisation Name:Organisation A,
Postcode: SW2 4DL,
Industry: School
},
123 {
Organisation Name:Organisation b,
Postcode: S2 5PS,
Industry: School
},
234 {
Organisation Name:Organisation C,
Postcode: EC2 3AD,
Industry: School
}
}
我的 PHP 代码设置是否尽可能有效?
当我在本地环境中运行它时,我收到一条错误消息,内容为:“LogicException:控制器必须返回响应([json 对象])”
所以我的 JSON 对象包含在错误消息中,这令人鼓舞,但不清楚为什么它是 LogicException 的一部分。
解决方案
也许你需要返回一个JsonResponse
use Symfony\Component\HttpFoundation\JsonResponse;
return new JsonResponse($json_object);
推荐阅读
- tinymce - TinyMCE 列表的问题
- python - 如何在不重新运行代码的情况下在 python 列表中生成随机值
- powershell - PowerShell:搜索所有属性值
- gpu - 如何在基于位置的动力学中并行化碰撞约束
- scala - 在 Akka Http 或 http4s 等库中编组的设计模式的名称是什么?
- tin-can-api - xAPI 语句查询以从 LRS 获取完成百分比
- ios - (UNITY) Xcode 中 IOS 的构建错误 -> -> "Lexical or Preprocessor Issue" -> 'FBSDKURLSession.h' file not found, FBSDKUserDataStore.h' file not found
- python - 如何从嵌套访问标签
- 没有使用美丽汤的类名或 id
- r - 计算R Shiny传单地图上点击点的距离
- css - 更改 wordpress 网站上特定页面而不是主菜单的悬停颜色