The program logic is faulty. could you please help me ;? Php $ arr & nbsp ;=& nbsp; array (0 & nbsp ;=& gt; & nbsp; array ('id' = & gt; 12, 'name' = & gt; 'No. 1 '), 1 & nbsp ;=& gt; & nbsp the program logic is faulty. please help me
$arr = array(
0 => array('id'=>12,'name'=>'NO.1'),
1 => array('id'=>13,'name'=>'NO.2'),
);
$_check_id = 0;
if($arr) {
foreach($arr as $v){
?>
" value="
" />
}
}?>
The initial state of the program is up.
Note that $ _ check_id is in three states. The first is 0, that is, $ _ check_id = 0, and the second is a value, but is not equal to the id in the array, that is, $ _ check_id = 2. the third state is: $ _ check_id is equal to the id in the array.
Now we need to compare $ _ check_id with the id in the array during the loop.
If they are equal, select radio in input, that is, the status is checked.
If not, select the first radio in the loop as checked.
Of course, you can also use a loop body to solve the above problem. it takes two or three hours to think about it. please give me some advice.
Of course, the array may also be empty, so there is no need to judge it. it is a good solution. now the trouble is how to solve the above problem. after thinking for a long time, there is no clue, and the head is big.
------ Best solution --------------------
$arr = array(
0 => array('id'=>12,'name'=>'NO.1'),
1 => array('id'=>13,'name'=>'NO.2'),
2 => array('id'=>14,'name'=>'NO.3'),
3 => array('id'=>15,'name'=>'NO.4'),
);
$_check_id = 14;
$found = false;
$htmls = array();
if($arr) {
foreach($arr as $v){
$input_pre = <<
EOT;
$input_post = <<
/>{$v['name']}
EOT;
if(!$found && $_check_id == $v['id']) {
$found = true;
$input_pre .= ' checked ';
}
$htmls[] = array($input_pre, $input_post);
}
}
$htmlstr = '';
foreach($htmls as $html) {
if(!$found) {
$html[0] .= ' checked ';
$found = true;
}
$htmlstr .= implode('', $html);
}
echo $htmlstr;
It can be executed directly.
------ Other solutions --------------------
$arr = array(
0 => array('id'=>12,'name'=>'NO.1'),
1 => array('id'=>13,'name'=>'NO.2'),
2 => array('id'=>14,'name'=>'NO.3'),
);
$_check_id = 0;
if($arr) {
foreach($arr as &$v) {
if($_check_id == $v['id']) {
$v['check'] = ' checked';
$_check_id = -1;
}
}
if($_check_id >=0) $arr[0]['check'] = ' checked';
foreach($arr as $v){
?>
" value="
"
/>
}
}?>
------ Other solutions --------------------
Foreach ($ arr as $ key => $ v ){
If ($ key = $ _ check_id ){
// Here is checked
Continue;
}
......