处理数组对象可以使用PHP内置的数组函数和面向对象的方式。
使用数组函数:
示例代码:
// 创建一个数组
$fruits = array(
"apple" => array(
"color" => "red",
"taste" => "sweet"
),
"banana" => array(
"color" => "yellow",
"taste" => "sweet"
),
"orange" => array(
"color" => "orange",
"taste" => "sour"
)
);
// 获取数组中某个元素
echo $fruits["apple"]["color"]; // 输出:red
// 遍历数组
foreach($fruits as $fruit){
echo $fruit["color"]. " ".$fruit["taste"]."<br>";
}
使用面向对象的方式:
示例代码:
// 创建一个水果类
class Fruit {
public $name;
public $color;
public $taste;
function __construct($name, $color, $taste) {
$this->name = $name;
$this->color = $color;
$this->taste = $taste;
}
function get_color() {
return $this->color;
}
function get_taste() {
return $this->taste;
}
}
// 创建一个水果对象数组
$fruits = array(
new Fruit("apple", "red", "sweet"),
new Fruit("banana", "yellow", "sweet"),
new Fruit("orange", "orange", "sour")
);
// 获取数组中某个元素
echo $fruits[0]->get_color(); // 输出:red
// 遍历数组
foreach($fruits as $fruit){
echo $fruit->get_color(). " ".$fruit->get_taste()."<br>";
}