在 PHP 中,可以使用數組和對象來保存復雜的數據結構。
數組是一種非常靈活的數據結構,可以容納多個值,并允許你通過鍵(索引)訪問這些值。數組可以包含任意類型的元素,包括其他數組。
示例:
$data = [
'name' => 'John',
'age' => 30,
'hobbies' => ['reading', 'traveling', 'sports'],
'address' => [
'street' => '123 Main St',
'city' => 'New York',
'country' => 'USA'
]
];
echo $data['name']; // 輸出 "John"
echo $data['hobbies'][1]; // 輸出 "traveling"
echo $data['address']['city']; // 輸出 "New York"
對象是一種更復雜的數據結構,它可以包含屬性和方法。在 PHP 中,可以使用類來定義對象的結構。
示例:
class Person {
public $name;
public $age;
public $hobbies;
public $address;
public function __construct($name, $age, $hobbies, $address) {
$this->name = $name;
$this->age = $age;
$this->hobbies = $hobbies;
$this->address = $address;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$person = new Person(
'John',
30,
['reading', 'traveling', 'sports'],
(object) ['street' => '123 Main St', 'city' => 'New York', 'country' => 'USA']
);
echo $person->getName(); // 輸出 "John"
echo $person->hobbies[1]; // 輸出 "traveling"
echo $person->address->city; // 輸出 "New York"
這兩種方法都可以用于保存復雜的數據結構。數組更簡單、靈活,而對象則提供了更好的封裝和面向對象編程的支持。根據實際需求選擇合適的方法。