I want to print all user names one by one which is array format, so instead of using foreach loop I am using array_walk() and it is printing all user data one by one but as per requirement data should be print in html table so defined one varaible $desc as empty and concatenate html code(table body table heading with users name) and at the end echo $desc but getting error:
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>';
?>
If I use without table it is working here is the code which I have use without table
<?php
$users=$this->db->get('users')->result();
function myfunction($value,$key)
{
echo $value->name;
}
$a = (array) $users;
array_walk($a,"myfunction");
?>
Output should print user name in html table assigned in $desc varaible using concatenation
Your function has no access to the
$descvariable. There is a way to resolve that but even then, it doesn't make sense to doecho $desc .= ....You're using
array_walkbut I think this could be a good use case for map instead. You want to map over the array and convert each element to an HTML string. That can then be mixed with implode to return all of the elements as a string.Example:
Why map? You'll often split up the process of generation and output. This gives you the option to do that. If you wanted to get your original code working there is a simple solution. Forget
$descaltogether and stick to echo. Echo the table opening, then walk the array, and finally the table closing.