如何解决如何通过在foreach中传递一个对象来循环数组
首先,请原谅我的无知,但我不知道如何解释(可能这个问题的标题不正确)。
我的程序:我创建了一个类,它的目的是根据传递给实例化对象(连接到数据库)的参数创建一个表。
我不知道该怎么做:我需要访问我的数组的位置(基于传递给我的值)。
我做了什么:如果我手动输入值(usuario
、apellido1
、apellido2
、email
),我的表格会生成,但我正在努力做到这一点。我尝试使用这行代码:$r->myObject->tableFields
但我认为,这在语法上是不正确的。
代码部分:
foreach ($res as $r){
$html .= '<tr>';
$html .= '<td>' . $r->$myObject->tableFields . '</td>'; # This code not works
// $html .= '<td>' . $r->usuario . '</td>'; # This code works
// $html .= '<td>' . $r->apellido1 . '</td>'; # This code works
// $html .= '<td>' . $r->apellido2 . '</td>'; # This code works
// $html .= '<td>' . $r->email . '</td>'; # This code works
$html .= '</tr>';
}
完整代码:
<?PHP
global $DB;
class GenerateCrud {
// Properties.
public $tableName;
public $id;
public $tableFields = array();
// Constructor.
function __construct($tableName,$id,$tableFields){
$this->tableName = $tableName;
$this->id = $id;
$this->tableFields = $tableFields;
//is_string($tableName) ? $this->tableName = $tableName : $this->tableName = null;
//is_string($id) ? $this->id = $id : $this->id = null;
//is_string($tableFields) ? $this->tableFields= $tableFields : $this-$tableFields = null;
}
}
$myObject = new GenerateCrud('users_test','id',['usuario','apellido1','apellido2','email']);
// Parse array to string.
$myStringArray = implode(",",$myObject->tableFields);
$sql = "SELECT $myStringArray FROM $myObject->tableName";
$res = $DB->get_records($sql);
// Generate HTML - START
$myArrayLength = count($myObject->tableFields);
$html = '<table>';
$html .= '<tr>';
foreach ($myObject->tableFields as $ths){
$html .= '<th>' . $ths . '</th>';
}
$html .= '</tr>';
foreach ($res as $r){
$html .= '<tr>';
$html .= '<td>' . $r->myObject->tableFields . '</td>'; # This code not works
// $html .= '<td>' . $r->usuario . '</td>'; # This code works
// $html .= '<td>' . $r->apellido1 . '</td>'; # This code works
// $html .= '<td>' . $r->apellido2 . '</td>'; # This code works
// $html .= '<td>' . $r->email . '</td>'; # This code works
$html .= '</tr>';
}
$html .= '</table>';
// Generate HTML - END
echo $html;
?>
我怎么能做到这一点,伙计们?我不是在寻找解决方案,只是寻求一些帮助或有关如何解决的建议。
我已经在互联网上搜索了一段时间,但我没有找到任何东西,因为我不知道如何描述我的问题。
先谢谢你! 快乐编码:)
解决方法
据我所知,$tableFields 是一个数组,因此您也必须遍历它。所以在你的 foreach 循环中试试这个。
foreach ($res as $r){
$html .= '<tr>';
foreach($myObject->tableFields as $field){
$html .= '<td>' . $r->$field . '</td>';
}
$html .= '</tr>';
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。