将值插入stdClass

时间:2015-10-12 20:13:17

标签: php

尝试在stdClass中添加数月,以便它看起来像

  • 2013
    • 二月 等...
  • 2014
    • 二月 等...
  • 2015
    • 二月 等...

使用以下代码:

$months = array(
             1=>'jan',
             2=>'feb',
             3=>'mars',
             4=>'april',
             5=>'may',
             6=>'june',
             7=>'july',
             8=>'aug',
             9=>'sep',
             10=>'oct',
             11=>'nov',
             12=>'dec');

foreach($months as $month){
        echo strtr($month,$months) .'<br>';
}

$years = array('2013',
               '2014',
               '2015');

$data = new stdClass;

foreach($years as $year){
    $data->year[] = $year;
    foreach($months as $month){
        $data->month[] = $months;
    }
}

foreach($data as $value){
    echo 'Year: '.$value->year.'<br>';
    echo 'Month: '.$value->month.'<br>';
}

但是var_dump很难阅读,似乎它将所有内容添加到37次。我真的不知道我做错了什么(或者我做错了什么?)

2 个答案:

答案 0 :(得分:1)

这就是所需要的,但您需要显示您期望的实际print_r()var_dump()

$data = new stdClass;

foreach($years as $year){
    $data->$year = $months;
}

然后:

foreach($data as $year => $months) {
    echo 'Year: '.$year.'<br>';
    foreach($months as $month) {
        echo 'Month: '.$month.'<br>';
    }
}

答案 1 :(得分:0)

我猜您的代码可以简化为:

<?php
$year = 2013;
while($year < 2016){
    echo $year;
    echo "<ul>";
for($i=1; $i < 13; $i++){
    $month = DateTime::createFromFormat('m', $i);
    echo "<li>".$month->format('M') . "</li>";
}
    echo "</ul>";
$year++;    
}
?>

<强>输出:

enter image description here