我有一個函數:如何在函數中使用foreach循環?
function animals($a,$b,$c,$d){
$pdo = Database::connect();
$sql = 'SELECT * FROM animals ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
echo "<td>".$a."</td>";
echo "<td>".$b."</td>";
echo "<td>".$c."</td>";
echo "<td>".$d."</td>";
}
}
我的問題是,我需要多次使用不同數量的參數,使用該功能。這意味着我的foreach循環,有時也有4項...
animals($row['a'],$row['b'],$row['c'],$row['d'],);
...有時有6項...
animals($row['e'],$row['f'],$row['g'],$row['h'],$row['i'],$row['j']);
...或有時3 ...
animals($row['k'],$row['l'],$row['m']);
...等等。所以,我不知道怎麼告訴我的功能,我的foreach物品的量而改變
更具體地講,如果我不使用的功能我的網頁看起來像這樣:
$pdo = Database::connect();
$sql = 'SELECT * FROM animals ORDER BY id DESC';
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home">
<?php
foreach ($pdo->query($sql) as $row) {
echo "<td>".$a."</td>";
echo "<td>".$b."</td>";
echo "<td>".$c."</td>";
echo "<td>".$d."</td>";
}
?>
</div>
<div role="tabpanel" class="tab-pane" id="profile">
<?php
foreach ($pdo->query($sql) as $row) {
echo "<td>".$row['a']."</td>";
echo "<td>".$row['b']."</td>";
echo "<td>".$row['c']."</td>";
echo "<td>".$row['d']."</td>";
}
?>
</div>
<div role="tabpanel" class="tab-pane" id="messages">
<?php
foreach ($pdo->query($sql) as $row) {
echo "<td>".$row['e']."</td>";
echo "<td>".$row['f']."</td>";
echo "<td>".$row['g']."</td>";
echo "<td>".$row['h']."</td>";
}
?>
</div>
<div role="tabpanel" class="tab-pane" id="settings">
<?php
foreach ($pdo->query($sql) as $row) {
echo "<td>".$row['i']."</td>";
echo "<td>".$row['j']."</td>";
}
?>
</div>
</div>
</div>
爲什麼你傳遞參數,如果你仍然在函數中運行查詢? –
@RakeshSharma什麼是arg? – Jarla
@DsRaj不,只有一個ID – Jarla