我已经为codeigniter表单设置了关联数组,并且我遇到了围绕数据进行foreach循环的问题。
我有这段代码 - 而且我现在才意识到我重新声明变量名$ array_name是一个数组而不是一个字符串,这就是为什么这个不能正常工作:<\ n / p>
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是一个数组而不是一个字符串,这就是为什么第一个不能正常工作,但我还是关于如何做到这一点有点困难。
答案 0 :(得分: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 );