使用html表单和php更新Json密钥

时间:2018-06-21 23:07:17

标签: php html json

我有一个json文件,如下,我想使用show_id作为键(使用支持unicode malayalam的php和html表单页面)将show_id作为键(标识显示值的唯一值)来更新showtime showend和showtitle

[
    {
      "day": "Sunday",
      "events": [

        {
          "show_id": "6231",
          "show_time": "02:00",
          "show_time_end": "03:00",
          "show_title": "SundayProgram5"
        },
        {
          "show_id": "6232",
          "show_time": "03:00",
          "show_time_end": "04:00",
          "show_title": "SundayProgram6"
        },
        {
          "show_id": "6234",
          "show_time": "04:00",
          "show_time_end": "05:00",
          "show_title": "SundayProgram7"
        },
        {
          "show_id": "6235",
          "show_time": "05:00",
          "show_time_end": "06:00",
          "show_title": "SundayProgram8"

          }
  ]
}

1 个答案:

答案 0 :(得分:1)

这将起作用-假设您正在获取json字符串,并在完成后希望以json字符串结尾。

// your data as a json string
$str = '{
      "day": "Sunday",
      "events": [

        {
          "show_id": "6231",
          "show_time": "02:00",
          "show_time_end": "03:00",
          "show_title": "SundayProgram5"
        },
        {
          "show_id": "6232",
          "show_time": "03:00",
          "show_time_end": "04:00",
          "show_title": "SundayProgram6"
        },
        {
          "show_id": "6234",
          "show_time": "04:00",
          "show_time_end": "05:00",
          "show_title": "SundayProgram7"
        },
        {
          "show_id": "6235",
          "show_time": "05:00",
          "show_time_end": "06:00",
          "show_title": "SundayProgram8"

          }
  ]
}' ;

// create an array out of your data
$json = json_decode($str,true) ;

// get your events into an array with the show_id as the index
$jsonByID = array() ;
foreach($json['events'] as $k=>$event) {
    $jsonByID[$event['show_id']] = $event ;
}    

// update your values using show_id
// your code here 
// example just for testing demonstrations 
$jsonByID[6235]['show_title'] = 'test' ;

// get your array back into the original format

foreach($json['events'] as $k=>$event) {
    $json['events'][$k] = $jsonByID[$event['show_id']] ;
}

// back to a json string
$updatedJson = json_encode($json) ;