duan1396
2015-11-17 21:21
浏览 606
已采纳

如何使用foreach循环中的现有数组值在PHP中创建新数组

I have an array ($datesandadults) with pairs of values which are the date and the number of people:

Array ( 
    [0] => stdClass Object ( 
            [thedate] => April 9, 2016 
            [theadults] => 6
        ) 
    [1] => stdClass Object ( 
            [thedate] => April 10, 2016 
            [theadults] => 9 
        )
...

I need to modify thedate value then put everything back into a new similar structured array. my code doesn't work, all it gives is:

Array ( 
    [0] => date 
    [1] => adults 
    [thedate] => 2016-04-09 
    [adults] => ) 

The code I am using is:

$final_results = array('thedate','adults');

foreach ($datesandadults as $res2) {
    foreach( $res2 as $key => $value) {
        if ($key=='thedate') {
            $actualtime=strtotime($value);
            $value = date('Y-m-d', $actualtime);
        }

        $final_results[thedate] = $res2->thedate;
        $final_results[adults] = $res2->adults;
    }
}

I know my current code is nonsense but maybe will give an idea what I need..

图片转代码服务由CSDN问答提供 功能建议

我有一个数组($ datesandadults),其中有一对值,即日期和人数:</ p>

 数组(
 [0] =&gt; stdClass对象(
 [thedate] =&gt; 2016年4月9日
 [theadults] =&gt; 6 
)\  n [1] =&gt; stdClass对象(
 [thedate] =&gt; 2016年4月10日
 [theadults] =&gt; 9 
)
 ... 
 </ code> </ pre> \  n 
 

我需要修改日期值,然后将所有内容放回到一个新的类似结构化数组中。我的代码不起作用,它给出的是:</ p>

 数组 (
 [0] =&gt; date 
 [1] =&gt; adult 
 [thedate] =&gt; 2016-04-09 
 [adult] =&gt;)
 </ code> </ pre  > 
 
 

我使用的代码是:</ p>

  $ final_results = array('thedate','adults'); 
 
foreach($ datesandadults  as $ res2){
 foreach($ res2 as $ key =&gt; $ value){
 if($ key =='thedate'){
 $ actualtime = strtotime($ value); 
 $ value =  DA  te('Ym-d',$ actualtime); 
} 
 
 $ final_results [thedate] = $ res2-&gt; thedate; 
 $ final_results [adults] = $ res2-&gt; adult; 
}  
} 
 </ code> </ pre> 
 
 

我知道我现在的代码是无稽之谈,但也许会让我知道我需要什么.. </ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题