我正在尝试设置一个表单,以允许用户更新大型JSON文件中的数据。我有一个表单,允许用户抓住他们想要的'事件'并进行编辑。当他们单击提交时,它会将数据发送到一个脚本,该脚本将整个JSON文件拉入一个数组。从那里,我需要脚本来搜索该数组,并找到与已编辑的“事件”具有相同ID的子数组的索引。因此,如果用户编辑了名为“William Bradford born”的条目,我需要脚本匹配ID“american-ccincore-1411541230”并为该子数组的索引返回0。
[
{
"id" : "american",
"title" : "A Timeline of American Literature",
"description" : "LENGTHY DESCRIPTIVE TEXT",
"initial_zoom" : "50",
"focus_date" : "1650-01-01 00:00:00",
"size_importance" : "true",
"timezone" : "-06:00",
"min_zoom" : "20",
"max_zoom" : "80",
"image_lane_height" : "50",
"display_zoom_level" : "1",
"tags" : {
"Puritan" : "0",
"Enlightenment" : "0",
"Romantic" : "0",
"Transcendental" : "0",
"Dark Romantic": "0",
"African American": "0",
"American Indian": "0",
"International" : "0"
},
"legend": [
{
"title": "Author event",
"icon": "star_red.png"
},
{
"title": "Publication event",
"icon": "square_blue.png"
},
{
"title": "Historical event",
"icon": "triangle_green.png"
}
],
"events": [
{
"id": "american-ccincore-1411541230",
"title": "William Bradford born",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "Puritan",
"startdate": "1950-03- 00:00:00",
"enddate": "1657-05- 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "https://www.csustan.edu/sites/default/files/ENGLISH/reuben/pal/chap1/bradford.gif",
"icon": "star_red.png",
"span_color": "#f66"
}, {
"id": "american-mforkner-1411364607",
"title": "Church Mission Society",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "",
"startdate": "1799-01-01 00:00:00",
"enddate": "1799-01-01 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "http://webarchive.cms-uk.org/_images/tnsaies1.jpg",
"icon": ".png",
"span_color": "#ccc"
}
]
}
]
我试图在这里修改十几个帖子中建议的脚本,但我无法在这种特殊情况下工作。谢谢你的任何建议。
答案 0 :(得分:0)
这只是一个简单的循环。需要注意的是,您需要区分0
的答案和未找到您要查找的事件。我通常使用false
表示失败,但这意味着稍后使用===
或!==
进行比较。
function findEventIndexById($events, $target) {
$retval = false;
foreach($events as $index=>$oneEvent) {
if ($oneEvent->id == $target) {
$retval = $index;
break;
}
}
return $retval;
}
$foundIndex = findEventIndexById($data->events, $eventId);
if ($foundIndex !== false) {
// ... do stuff here to $data->events[$foundIndex]
} else
// ... report an error ...