插件窝 干货文章 php 数组转stdobject

php 数组转stdobject

数组 转换 stdClass 对象 331    来源:    2025-03-19

在 PHP 中,你可以使用 json_decodejson_encode 函数将数组转换为 stdClass 对象。stdClass 是 PHP 的一个内置类,通常用于创建匿名对象。

以下是一个简单的示例,展示如何将数组转换为 stdClass 对象:

<?php
// 定义一个数组
$array = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
];

// 将数组转换为 JSON 字符串
$jsonString = json_encode($array);

// 将 JSON 字符串转换为 stdClass 对象
$stdObject = json_decode($jsonString);

// 输出 stdClass 对象
print_r($stdObject);
?>

解释:

  1. json_encode($array): 将数组转换为 JSON 字符串。
  2. json_decode($jsonString): 将 JSON 字符串转换为 stdClass 对象。

输出结果:

stdClass Object
(
    [name] => John Doe
    [age] => 30
    [email] => john.doe@example.com
)

直接转换:

如果你不想通过 JSON 字符串进行转换,也可以直接使用类型转换将数组转换为 stdClass 对象:

<?php
// 定义一个数组
$array = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
];

// 将数组直接转换为 stdClass 对象
$stdObject = (object) $array;

// 输出 stdClass 对象
print_r($stdObject);
?>

输出结果:

stdClass Object
(
    [name] => John Doe
    [age] => 30
    [email] => john.doe@example.com
)

注意事项:

  • 使用 (object) 进行类型转换时,数组的键名将成为 stdClass 对象的属性名。
  • 如果数组的键名是数字,它们将被转换为字符串形式的属性名。

这两种方法都可以将数组转换为 stdClass 对象,选择哪种方法取决于你的具体需求和偏好。