如何遍历数组然后替换匹配id的数据

时间:2012-04-25 17:16:36

标签: php arrays iteration

好吧我正在尝试做的是迭代通过Json解码数组然后搜索ID(键)然后将该数据发布到表单进行编辑然后编码然后保存它看起来像这么简单的任务但是我是不使用数据库或java或java脚本我必须只使用Json,PHP和HTML我的主代码(Controller)文件如下

<?php

$file_name = 'engagements.json'; // Serialized speaking engagments

/**
* Controller for Speaking Engagements
*/

if (!isset($_REQUEST['act']) || !$action = $_REQUEST['act']){
  $action = 'list';
} //End If

switch ($action) {
  case 'list': // List
    $json_data = file_get_contents($file_name);
    if (!$engagements = json_decode($json_data, true)) { // Convert serialized data to               array
      $engagements = array();
    } //End If
    include 'engagements_list.phtml';
    break;

  case 'view': // View
    $json_data = file_get_contents($file_name);
    $temp_array = json_decode($json_data);

    foreach($temp_array as $key=>$id){
      if($id->ID == 2){
        echo "got it \n";
        echo "ID: $id->ID \n";
        echo "Title: $id->Title \n";
        echo "Description: $id->Description \n";
      }// End If
    }
    break;

  case 'add': // Add
    $temp_array = array();
    $file = file_get_contents($file_name);
    $json_data = json_decode($file);
    $high_value = count($json_data);
    $high_value++;
    $temp_array['ID'] = $high_value;
    $temp_array['Title'] = $_POST['Title'];
    $temp_array['Description'] = $_POST['Description'];
    $json_data[] = $temp_array;
    file_put_contents($file_name, json_encode($json_data));

    include 'engagements_add.phtml';
    break;

  case 'edit': // Edit

    $file = file_get_contents($file_name);
    $json_data = json_decode($file, true);

    // what comes next here

    include 'engagements_edit.phtml';
    break;

  case 'delete': // Delete
    break;

  default:
    throw(new Exception('Invalid action given'));
    break;
}//End Switch

exit;

<!-- Edit View -->
<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">
  <table>
    <tr><td><input type="hidden" name="ID"></td></tr>
    <tr><td><input type="text" style="width:500px;" name="Title"></td></tr>
    <tr><td><textarea cols="40" rows="2" style="width: 500px; height:250px;" name="Description"></textarea></td></tr>
    <tr><td><input type="submit" name="Submit" value="Submit"/></td></tr>
  </table>
</form>

请帮助我,我到处搜索答案,但可以找到解释如何正确执行此操作的资源

1 个答案:

答案 0 :(得分:0)

微小的一点。

<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">

我假设你打算这样打字:

<form action="engagements.php?act=edit&ID=<?php echo $_GET['ID']?>" method="get">

$_GET语句也缺少echo

<强>更新

我发现php关闭标记?>在EDIT VIEW之前丢失了。并且'查看'部分在交换机中,为什么你回显ID属性?它可能如下:

echo "ID: $id['ID'] \n";