[英]PHP class with 3 objects iterate through array
I have to demonstrate PHP class with 3 objects of that class, then add these class objects to an array, and iterate through the array displaying the object data variable values in an HTML table.我必须用该类的 3 个对象来演示 PHP 类,然后将这些类对象添加到一个数组中,并遍历该数组,在 HTML 表中显示对象数据变量值。 I was not able to even echo values without a table, not sure what is wrong there.我什至无法在没有表格的情况下回显值,不确定那里出了什么问题。 Here is what I got so far.这是我到目前为止所得到的。
<?php
$output ='';
class car {
public $make;
public $model;
public $year;
function set_make($make) {
$this->make = $make;
}
function set_model($model) {
$this->model = $model;
}
function set_year($year) {
$this->year = $year;
}
function get_make() {
return $this->make;
}
function get_modele() {
return $this->model;
}
function get_year() {
return $this->year;
}
}
$car1 = new Car();
$car1->set_make('Toyota');
$car1->set_model('Rav4');
$car1->set_year('2018');
$car2 = new Car();
$car2->set_make('Acura');
$car2->set_model('ILX');
$car2->set_year('2012');
$carArray = array();
array_push( $carArray, $car1, $car2);
$output .= '<TABLE border="2" align="left">';
$output .= "<TR>";
$output .= '<TH align="left">' . "Make" . "</TH>";
$output .= '<TH>' . "Model" . "</TH>";
$output .= '<TH>' . "Year" . "</TH>";
$output .= "</TR>";
return $output;
try this:尝试这个:
$output ='';
class car {
public $make;
public $model;
public $year;
function set_make($make) {
$this->make = $make;
}
function set_model($model) {
$this->model = $model;
}
function set_year($year) {
$this->year = $year;
}
function get_make() {
return $this->make;
}
function get_modele() {
return $this->model;
}
function get_year() {
return $this->year;
}
}
$car1 = new Car();
$car1->set_make('Toyota');
$car1->set_model('Rav4');
$car1->set_year('2018');
$car2 = new Car();
$car2->set_make('Acura');
$car2->set_model('ILX');
$car2->set_year('2012');
$carArray = array();
array_push( $carArray, $car1, $car2);
$final_array = json_decode(json_encode($carArray), true);
$output = '<table>';
$output .= '<tr><th>Make</th><th>Model</th><th>Year</th></tr>';
foreach ($final_array as $key => $car_data) {
$output .= '<tr><td>'.implode('</td><td>', $car_data).'</td></tr>';
}
$output .= '</table>';
echo $output;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.