如何对foreach循环中的数组进行计数?另外,这是编写代码的最佳方式吗?还是有更多的包罗万象?我有一个三维数组(3层)。
下面是print_r
中的示例Array
(
[0] => Array
(
[0] => 17
[audit_inspectionID] => 17
[1] => 2016-08-15
[created] => 2016-08-15
[2] => 2016-08-15 09:52:28
[modified] => 2016-08-15 09:52:28
[class_answer] => Array
(
[0] => Needs Improvement
[1] => Need To Correct
[2] => Needs Immediate Action
)
)
)
下面是PHP代码:
$newArray = [];
foreach($requirements as $key => $value){
$newArray[] = $value['audit_inspectionID'];
$newArray[] = $value['requirement'];
$newArray[] = $value['class_answer'];
$newArray[] = $value['repeat_answer'];
$newArray[] = $value['class_answer'];
$newArray[] = $value['actionID'];
$newArray[] = $value['action_link'];
print "<div id='inspection_view" . $value['audit_inspectionID'] . "' style='display:inline'>
<table id='actions_table' class='table table-bordered table-condensed table-striped bg-info'>
<thead>
<th align='center'>" . value['requirement'] . " </th>
". if ($corporate_admin == 'true') { ."
<a id='" . $value['audit_inspectionID'] . "' class='btn btn-danger pull-right remove1' href=' + '#' + '>Remove</a><a id='edit" . $value['audit_inspectionID'] ."' class='btn btn-warning pull-right edit1' href=#>Edit</a></th>
". } ."
</thead><tbody>
<tr>
<td>
for循环如何计数这个数组?
". for (x = 0; x< count($value[class_answer]) ; x++){
$value[class_answer]
} ."
<br>
". $value[repeat_answer] ."
<br>
". if ($value[actionID] != 0) {
$value[action_link]
} ."
</td>
</tr>
</tbody>
</table>
</div>";/**/
}
不能在print
语句中放入for
或if
等其他语句。结束print
语句,然后使用一个新语句执行所需操作。
print "<div id='inspection_view" . $value['audit_inspectionID'] . "' style='display:inline'>
<table id='actions_table' class='table table-bordered table-condensed table-striped bg-info'>
<th align='center'>" . value['requirement'] . " </th>
<tr>
<td>";
foreach ($value['class_answer'] as $ans) {
print "$ans ";
}
print "<br>
".$value[repeat_answer]."
<br>";
if ($value['actionID'] != 0) {
print $value['action_link'];
}
print "</td>
</tr>
</tbody>
</table>
</div>";
您可以运行语句并稍后打印出来。我会这样做
print "<div id='inspection_view" . $value['audit_inspectionID'] . "' style='display:inline'>
<table id='actions_table' class='table table-bordered table-condensed table-striped bg-info'>
<th align='center'>" . value['requirement'] . " </th>
<tr>
<td>";
$count=0;
for (x = 0; x< count($value[class_answer]) ; x++){
$count++;
}
print "<br>". $value[repeat_answer] ."<br>";
if ($value[actionID] != 0) {
print $value[action_link];
}
print "</td>
</tr>
</tbody>
</table>
</div>";
$value[class_answer]中的元素个数为$count
print $count