2

我已经为 codeigniter 表单设置了关联数组,并且遇到了围绕数据进行 foreach 循环的问题。

我有这段代码 - 我现在刚刚意识到我将变量名 $array_name 重新声明为一个数组而不是一个字符串,这就是为什么这个不起作用:

foreach ($search as $search_term){
$count++;
$array_name = '$search'.$count;

$array_name = array(
        'name'  => 'search'.$count,
        'id'    => 'search'.$count,
        'value' => set_value('search'.$count, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
);

}

然而,数组名称被记录为 $array_name 而不是 $search1,所以我显然做错了,我希望有人能指出我正确的方向!

我也试过这个:

foreach ($search as $search_term){
$count++;
$array_name = '$search'.$count;

'search'.$count = array(
        'name'  => 'search'.$count,
        'id'    => 'search'.$count,
        'value' => set_value('search'.$count, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
);

}

这是我正在寻找的最终结果,但总共会有六个:

$search1 = array(
        'name'  => 'search'.$count,
        'id'    => 'search'.$count,
        'value' => set_value('search'.$count, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
);
$search2 = array(
        'name'  => 'search2',
        'id'    => 'search2',
        'value' => set_value('search2, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
);

编辑1:

我刚刚意识到我将变量名 $array_name 重新声明为一个数组而不是一个字符串,这就是第一个不起作用的原因,但我仍然有点不知道该怎么做。

4

1 回答 1

3

使用动态字符串创建变量${'somestring'} =

foreach ($search as $search_term){
    $count++;
    $array_name = '$search'.$count;

    ${'search'.$count} = array(
        'name'  => 'search'.$count,
        'id'    => 'search'.$count,
        'value' => set_value('search'.$count, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
    );
}

虽然使用关联数组会更好

$searches = array();
foreach ($search as $search_term){
    $count++;
    $array_name = '$search'.$count;

    $searches['search'.$count] = array(
        'name'  => 'search'.$count,
        'id'    => 'search'.$count,
        'value' => set_value('search'.$count, $search_term),
        'maxlength' => 80,
        'size'  => 30,
        'class' => 'text-input',
    );
}

print_r( $searches );
于 2013-08-01T09:44:42.787 回答