【发布时间】:2019-08-11 05:20:10
【问题描述】:
我想一一打印所有用户名,这是数组格式,所以我不使用 foreach 循环,而是使用 array_walk(),它一一打印所有用户数据,但根据要求,数据应以 html 格式打印桌子 因此将一个变量 $desc 定义为空并连接 html 代码(表体表标题与用户名),最后 echo $desc 但出现错误:
expected output:
<html>
<body>
<h2>Basic HTML Table</h2>
<table >
<tr>
<th>username</th>
</tr>
<tr>
<td>user1</td>
</tr>
<tr>
<td>user2</td>
</tr>
<tr><td>user3</td></tr>
<tr><td>user4</td></tr>
<?php
$users=$this->db->get('users')->result();
$desc = '';
$desc .= '<table class="table table-hover" id="catgeory_list">
<thead>
<tr>
<th>User Name</th>
</tr>
</thead>
<tbody>';
function myfunction($value)
{
echo $desc .= '<tr><td>'.$value->name.'</td></tr>';
}
$a = (array) $users;
array_walk($a,"myfunction");
$desc .= '</tbody></table>';
?>
如果我不使用表格,它在这里工作的是我使用不带表格的代码
<?php
$users=$this->db->get('users')->result();
function myfunction($value,$key)
{
echo $value->name;
}
$a = (array) $users;
array_walk($a,"myfunction");
?>
输出应打印html 表中的用户名,该表使用连接在$desc 变量中分配
【问题讨论】:
-
myfunction无法访问global 变量$desc并且在函数内部它是未定义的。 -
将
$desc分配到函数中 -
让我们知道接下来会发生什么
-
@Nipun Tharuksha 是的,根据您的建议,我使用 global 关键字没有收到任何错误,但输出不在 html 表中,数据也重复
-
数组遍历在这里不是正确的方法,您应该使用 foreach 循环
标签: php html array-walk