PHP forach 对象数组

问题描述 投票:0回答:1

如何在 foreach 循环中使用对象来回显该 PHP 数组? 我想在代码的不同部分回显每个值。

array(2) {
  ["new_years_day"]=>
  object(DateTime)#1 (3) {
    ["date"]=>
    string(26) "2024-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(16) "America/New_York"
  }
  ["juneteenth"]=>
  object(DateTime)#2 (3) {
    ["date"]=>
    string(26) "2024-06-19 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(16) "America/New_York"
  }
}

我尝试了这段代码,但它不起作用($holidaysThisYear 是数组的名称):

<?php foreach($holidaysThisYear as $holidayThisYear) {
  echo $holidayThisYear->timezone;
} ?>
php datetime
1个回答
0
投票

使用时必须使用相关的类方法。在你的情况下

getTimezone()
getName()

<?php
$holidaysThisYear = [
    "new_years_day" => new DateTime("2024-01-01 00:00:00.000000"),
    "juneteenth" => new DateTime("2024-06-19 00:00:00.000000")
];


foreach($holidaysThisYear as $holidayThisYear) {
    echo $holidayThisYear->getTimezone()->getName();
    echo PHP_EOL;
}

在线玩PHP

© www.soinside.com 2019 - 2024. All rights reserved.