首页 > 解决方案 > 从 stdClass 对象中提取特定值

问题描述

我在 $response 中包含以下 stdClass 对象:

stdClass Object ( [domain] => stdClass Object ( [id] => d1111111 [spamscore] => 75 [rejectscore] => 200 ) [domainalias] => Array ( ) [wildcard] => Array ( ) [catchall] => Array ( ) [forward] => Array ( ) [mailbox] => Array ( 

[0] => stdClass Object ( [highEmailNotification] => [id] => m1111111 [lastPasswordChange] => 2020-02-19T22:41:12+00:00 [local] => mailbox1 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[1] => stdClass Object ( [highEmailNotification] => [id] => m2222222 [lastPasswordChange] => 2020-02-17T15:46:21+00:00 [local] => mailbox2 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[2] => stdClass Object ( [highEmailNotification] => [id] => m3333333 [lastPasswordChange] => 2020-02-19T15:00:36+00:00 [local] => mailbox3 [lowEmailNotification] => [quotaMB] => 1024 [receive] => 1 [rejectscore] => 0 [send] => 1 [spamscore] => 75 [usageMB] => 0 [enabled] => 1 ) ) [spamblacklist] => Array ( ) [spamwhitelist] => Array ( ) [responder] => Array ( ) [name] => domain.com )

我需要将其转换为数组并从中提取特定值,即 [id] 和 [local]。

速度也是一个问题,因为这个数组会增长到数千个项目,所以如果有其他比“foreach”更快的方法会更好。

我使用了这里的一些建议,例如:

$array = json_decode(json_encode($response), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "<br>";
}

并取得了部分成功:

d1111111 -

-

-

-

- 我 - 我

(所以它找到了第一个 [id] 值)

然而,它错过了我所追求的最重要的价值观。

我需要得到的是:

m1111111 - 邮箱1

m2222222 - 邮箱2

m3333333 - 邮箱3

非常感谢任何建议。

标签: arraysobjectstdclass

解决方案


您尝试打印的值位于$response.

尝试这个。

$array = json_decode(json_encode($response['mailbox']), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "<br>";
}

推荐阅读