【发布时间】:2021-08-26 07:29:41
【问题描述】:
首先,请原谅我的无知,但我不知道如何解释(可能这个问题的标题不正确)。
我的程序:我创建了一个类,它的目的是根据传递给实例化对象(它连接到数据库)的参数创建一个表。
我不知道该怎么做:我需要在 for each 中访问我的数组的位置(基于传递给我的值)。
我做了什么:如果我手动输入值(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;
?>
我怎么能这样做,伙计们?我不是在寻找解决方案,只是寻求一些帮助或一些关于如何解决的建议。
我已经在互联网上搜索了一段时间,但我没有找到任何东西,因为我不知道如何描述我的问题。
提前感谢您! 快乐编码:)
【问题讨论】:
-
您是否尝试过
var_dump($r);来查看值是什么。看起来 myObject->tableFields 实际上是对象的属性 -
是的!
$r包含我的查询的所有值。因此,如果我访问$myObject->tableFields,我将获得 4 个表字段,因为我处于循环中(usuario、apellido1、apellido2、email),但我不能将其与 @ 987654336@,你知道我想说什么吗? -
使用此处显示的 foreach 的第二个语法版本 php.net/manual/en/control-structures.foreach.php,然后您可以访问循环体内的键 和 值。
-
谢谢你,你说得对,我得稍微修改一下我的 foreach 结构。谢谢!
标签: php loops class object foreach