在 PHP 中,處理復雜數據結構的常用方法是使用數組和對象
$students = [
['name' => 'Alice', 'age' => 20, 'major' => 'Computer Science'],
['name' => 'Bob', 'age' => 22, 'major' => 'Mathematics'],
['name' => 'Charlie', 'age' => 21, 'major' => 'Physics']
];
foreach ($students as $student) {
echo "Name: " . $student['name'] . "<br>";
echo "Age: " . $student['age'] . "<br>";
echo "Major: " . $student['major'] . "<br><br>";
}
class Student {
public $name;
public $age;
public $major;
public function __construct($name, $age, $major) {
$this->name = $name;
$this->age = $age;
$this->major = $major;
}
public function display() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age . "<br>";
echo "Major: " . $this->major . "<br><br>";
}
}
$students = [
new Student('Alice', 20, 'Computer Science'),
new Student('Bob', 22, 'Mathematics'),
new Student('Charlie', 21, 'Physics')
];
display
方法:foreach ($students as $student) {
$student->display();
}
這些示例展示了如何使用 PHP 處理復雜數據結構并顯示其內容。你可以根據需要調整代碼以適應不同的數據結構和顯示需求。