1

我将字段名称存储在一个数组中,希望能够动态创建变量。

我收到 if 和 else 的非法偏移类型错误,这两行:

$data[$tmp_field] = $tmp_field[$id];

$data[$tmp_field] = 0;

我检查了发布数据,它使用适当的数据发布,但我不确定问题是什么。

$student_id 存储所有学生的 id。例如:$student_id = array(8,9,11,23,30,42,55);

function updateStudentInfo() {
  $student_id = $this->input->post('student_id');
  $internet_student = $this->input->post('internet_student');
  $dismissed = $this->input->post('dismissed');
  $non_matriculated_student = $this->input->post('non_matriculated_student');
  $felony = $this->input->post('felony');
  $probation = $this->input->post('probation');
  $h_number = $this->input->post('h_number');
  $office_direct_to = $this->input->post('office_direct_to');
  $holds = $this->input->post('holds');

  $fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');

  foreach($student_id as $id):
    $data = array();

    foreach($fields as $field_name):
      $tmp_field = ${$field_name};

      if(empty($tmp_field[$id])) {
        $data[$tmp_field] = 0;
      } else { 
        $data[$tmp_field] = $tmp_field[$id];
      }
    endforeach;

    print '<pre style="color:#fff;">';
    print_r($data);
    print '</pre>';

  endforeach;
}

这是我想要的数组格式:

Array
(
    [internet_student] => 1
    [non_matriculated_student] => 1
    [h_number] => 0
    [felony] => 0
    [probation] => 1
    [dismissed] => 0
)

添加了屏幕截图,让您直观地了解发布数据的表单

在此处输入图像描述

4

2 回答 2

1
foreach($student_id as $id):
    $data = array();

    foreach($fields as $field_name):
      $tmp_field = ${$field_name};

      if(empty($tmp_field[$id])) {
        $data[$field_name] = 0;
      } else { 
        $data[$field_name] = $tmp_field[$id];
      }
    endforeach;

    print '<pre style="color:#fff;">';
    print_r($data);
    print '</pre>';

  endforeach;
于 2012-08-02T15:25:50.800 回答
0

我假设所有这些字段都是数组,否则你不需要任何循环。

function updateStudentInfo()
{
    $student_id                 = $this->input->post('student_id');
    $internet_student           = $this->input->post('internet_student');
    $dismissed              = $this->input->post('dismissed');
    $non_matriculated_student   = $this->input->post('non_matriculated_student');
    $felony                     = $this->input->post('felony');
    $probation              = $this->input->post('probation');
    $h_number                   = $this->input->post('h_number');
    $office_direct_to           = $this->input->post('office_direct_to');
    $holds                  = $this->input->post('holds');

    $fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');

    $student_count  = count($student_id);
    foreach($student_id as $id)
    {
        $data   = array();
        foreach($fields as $field)
        {
            if(array_key_exists($id, $$field))
                $data[$field]   = ${$field}[$id];
        }
    }
}

您正在尝试将学生 id 用作其他字段的数组键,但 HTML 表单只是一个标准索引数组,未键入任何学生数据。

于 2012-08-02T15:07:15.513 回答