Sol Sol - 3 months ago 9
PHP Question

How do you count a multidimensional array to put in a foreach loop (in php)?

How do you count an array for a foreach loop? Also, is this the best way to write this code or is there more of a catchall? I have a 3 dimensional array(3 levels).

Here is an example from 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
)
)

)


Here is the PHP code:

$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>


How can I count this array for this for loop?

". 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>";/**/
}

Answer

You can't put a other statements like for or if inside a print statement. End the print statement, then use a new statement to do what you want.

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>";