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. 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;
Advertisement
Answer
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;