繁体   English   中英

PHP:根据给定值在多维数组中查找数组的索引

[英]PHP: Find index of array in multidimentional array based on given value

我正在尝试设置一个表单,以允许用户更新大JSON文件中的数据。 我有一个表格,允许用户获取他们想要的“事件”并进行编辑。 当他们单击提交时,它将数据发送到脚本,该脚本将整个JSON文件提取到数组中。 从那里,我需要脚本来搜索该数组,并找到与已编辑的“事件”具有相同ID的子数组的索引。 因此,如果用户编辑了名为“ William Bradfordborn”的条目,则我需要脚本来匹配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和未能找到您要查找的事件。 我通常使用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 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM