You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何访问对象数组?遍历数组及字符串长度疑问

问题描述

我执行var_dump($_REQUEST);得到以下结果:

array(1) { ["email"]=> array(2) { [0]=> string(15) "email1@example.com" [1]=> string(15) "email2@example.com" } }

请问如何遍历该数组,以得到如下形式的结果:

$email[0]=email1@example.com
$email[1]=email2@example.com

更新: 已修正索引
更新2:
我使用了如下代码:

$email = $_REQUEST['email'];
var_dump($email);

但得到的结果为:

array(2) { [0]=> string(18) "email1@example.com" [1]=> string(18) "email2@example.com" }

同时想了解PHP中如何访问对象数组。

解决方案

一、遍历数组生成指定格式输出

从你的var_dump结果来看,$_REQUEST['email']本身就是包含两个元素的索引数组,直接遍历即可生成目标格式:

方法1:for循环(适用于连续索引数组)

$email = $_REQUEST['email'];
for ($i = 0; $i < count($email); $i++) {
    echo "\$email[$i]=" . $email[$i] . "\n";
}

方法2:foreach循环(适配任意索引类型数组)

$email = $_REQUEST['email'];
foreach ($email as $index => $value) {
    echo "\$email[$index]=$value\n";
}

两种方法都会输出你需要的内容:

$email[0]=email1@example.com
$email[1]=email2@example.com

二、PHP中访问对象数组

对象数组指数组元素为对象的情况,访问时需先获取数组中的对象,再通过->操作符访问对象的属性或方法:

示例场景

先定义一个简单的类并创建对象数组:

class User {
    public $email;
    public function __construct($email) {
        $this->email = $email;
    }
}

// 构建对象数组
$userList = [
    new User('email1@example.com'),
    new User('email2@example.com')
];

访问方式

  1. 直接通过索引访问:
echo $userList[0]->email; // 输出 email1@example.com
echo $userList[1]->email; // 输出 email2@example.com
  1. 遍历批量访问:
foreach ($userList as $index => $user) {
    echo "\$userList[$index]->email=" . $user->email . "\n";
}

输出结果:

$userList[0]->email=email1@example.com
$userList[1]->email=email2@example.com

如果对象属性为私有/受保护,需通过类的公共方法访问:

class User {
    private $email;
    public function __construct($email) {
        $this->email = $email;
    }
    public function getEmail() {
        return $this->email;
    }
}

// 调用公共方法获取属性
echo $userList[0]->getEmail(); // 输出 email1@example.com

内容的提问来源于stack exchange,提问作者Guru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 06:11:18