我正在学习 PHP 和 code igniter,总体上对现代编程不熟悉,所以请多多包涵!
我编写了一个函数,用于从 mysql 表中生成每周骑自行车的总公里数。我的功能是生成一个包含 Std Class 对象的多维数组。当我尝试在 View 文件中回显结果时,出现错误:错误:消息:类 stdClass 的对象无法转换为字符串。
我已经尝试了关于如何在大约十个线程中为多维数组创建 foreach 循环的说明,包括 this one .看来我需要一个嵌套的 foreach 结构,但是,我不明白如何将这些示例应用到我的代码中。
//在我的 Controller 索引函数中
$weeknumber = array(0, 1, 2, 3, 4, 5, 6, 7);
$bikedata['sums_for_table'] = array_map(array($this->bike_model,
'get_weekly_sum'), $weeknumber);
//在我的模型中
public function get_weekly_sum($when)
{
$this->db->select_sum('distance');
$this->db->where("WEEK (date) = WEEK( current_date ) - $when AND YEAR( date) = YEAR( current_date)");
$query = $this->db->get('bike_stats');
return $query->result();
//在我看来(为简单起见进行了修剪。它实际上是一张 table 。)
foreach ($sums_for_table as $sum_array):
foreach ($sum_array as $key => $object):
echo $object;
endforeach;
endforeach;
该函数工作正常,因为函数返回的数组(下面,来自 var_dump)包含我想要的信息(数字 63.2 等),但我无法理解如何使用其中的信息形式。
array(8) {
[0]=> array(1) { [0]=> object(stdClass)#23 (1) { ["distance"]=> string(4) "63.2" } }
[1]=> array(1) { [0]=> object(stdClass)#24 (1) { ["distance"]=> string(5) "111.9" } }
[2]=> array(1) { [0]=> object(stdClass)#25 (1) { ["distance"]=> string(4) "48.2" } }
[3]=> array(1) { [0]=> object(stdClass)#26 (1) { ["distance"]=> NULL } }
[4]=> array(1) { [0]=> object(stdClass)#27 (1) { ["distance"]=> string(4) "26.7" } }
[5]=> array(1) { [0]=> object(stdClass)#28 (1) { ["distance"]=> string(4) "42.2" } }
[6]=> array(1) { [0]=> object(stdClass)#29 (1) { ["distance"]=> string(4) "32.3" } }
[7]=> array(1) { [0]=> object(stdClass)#30 (1) { ["distance"]=> string(4) "10.9" } } }
我的主要问题是如何修复我的 View 文件代码以正确输出此数组中的数字。但是,如果我可以用不同的方式编写我的函数来生成常规关联数组,我也很想知道!
任何帮助将不胜感激!
最佳答案
这应该可以解决问题:
foreach ($sums_for_table as $entry) {
$distance = $entry[0]->distance;
echo $distance . ' <br />';
}
您可以使用 $object->property 语法访问 stdClass 对象的属性。
我不知道你所有的代码是如何工作的,因为我没有看到所有的代码,但你可以尝试一种更简洁的方法:
// controller
$bikedata['sums_for_table'] = [];
$weeknumbers = array(0, 1, 2, 3, 4, 5, 6, 7);
foreach ($weeknumbers as $weeknumber) {
$weekResult = $this->bike_model->get_weekly_sum($weeknumber);
$bikedata['sums_for_table'][$weeknumber] = $weekResult[0]->distance;
}
// view
foreach ($sums_for_tables as $weekNumber => $distance) {
// draw your table here
}
关于php - 使用 StdClass 对象为多维数组创建 foreach 循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205321/