1 回答
TA贡献1824条经验 获得超6个赞
请查看代码中的注释以了解更改的内容以及原因
基本上,您将 json 文件转换为数组,因此您必须将$data
其作为数组进行寻址以获取其值。
检查此人是否已存在的代码应该在循环内,因为您希望在处理 json 文件中的一组人时检查每个人。
现在我们知道你的 JSON 文件真的没有帮助,也不配得上 JSON 这个名字......
示例文件
{ "John Doe": "John Doe", "Jane Doe": "Jane Doe" }
代码需要是
$file = file_get_contents('file.json');
$jsonData = json_decode($file, true);
foreach ($jsonData as $data) {
// Split the single field into Firstname and lastname
$name = explode(' ', $data);
$exists = $this->getMyRepository()->findOneBy([
'first_name' => $name[0],
'last_name' => $name[1]
]);
if ($exists) {
// this person already in the database
// thats cool, just dont try and insert them again
continue;
} else {
// again in here you are getting data from an array
// called `$data` and not an entity with getters and setters
$new = new MyEntity();
$new->setFirstName($name[0]);
$new->setLastName($name[1]);
$this->em->persist($new);
}
}
}
$this->em->flush();
}
大警告此代码依赖于 JSON 数据文件,该文件始终具有由空格分隔的名字和姓氏。 这是一件非常危险的事情,值得信赖
你真的应该回到创建这个 JSON 文件的人那里,然后要求正确地做它!!!
- 1 回答
- 0 关注
- 189 浏览
添加回答
举报