访问 PHP 数组对象中的项目

Accessing items within a PHP array object

我有一个从 SQL 服务器数据库中检索到的记录数组,存储在一个对象 $result 中。我想访问数组对象中的每个项目并将其打印到屏幕上。我怎样才能做到这一点?我的尝试低于

$result = $DB->get_records_sql("SELECT  rawname, ID FROM mdl_tag where tagType = 'institution'"); 
$result = array();
        foreach ($result as $ $value) {
        echo $value;
        );
    }

正确代码如下:

// Get results from table 'tag', where 'tagtype' matches 'institution', with no sorting and returning fields 'id' and 'rawname'.
$results = $DB->get_records('tag', ['tagtype' => 'institution'], '', 'id, rawname');
foreach ($results as $value) {
    echo $value->rawname;
}

所以,有很多问题:

  1. 使用get_records,除非你真的需要使用get_records_sql.
  2. 如果你需要使用get_records_sql,那么table被称为{tag}而不是mdl_tag,否则你' ll 运行 在使用 'mdl_' 以外的前缀的任何服务器上都会出现问题(例如,当 运行ning phpunit 或 behat 测试时)。
  3. 写入 $result = array();在循环结果之前立即从数据库中丢弃详细信息并用空数组替换它们
  4. get_records(或get_records_sql)的结果是一个包含对象的数组,每个对象包含请求字段的值,因此您需要访问单个值,而不是尝试回显整个对象
  5. Moodle 中的所有数据库字段都是小写的,所以 'tagtype' 不是 'tagType','id' 不是 'ID'。