dora12345678 2013-09-11 01:43
浏览 25
已采纳

PHP:合并具有相同标题的数组

I have some php arrays from a loop, all of them bearing the same name. Now I want to merge them, but it seems not to work...

Here's my loop:

while($row = mysql_fetch_row($sql1)){
    $startzeit=strtotime($row[2]);
    $endzeit=strtotime($row[3]);
    $startzeit_format = date("Y-m-d",$startzeit);
    $endzeit_format = date("Y-m-d",$endzeit);
    $datearray[] = createDateRangeArray($startzeit_format,$endzeit_format);
    }

This should be the merging code:

for($i = 0; $i<count($datearray); $i++)
    {
    $datesarray = array_merge($datearray[$i]);
    }

Anyway, the manual merge works fine:

$datesarray = array_merge( $datearray[0], $datearray[1], $datearray[2], $datearray[3]); 

This one leads to the desired output. However I'd like to automatize it, as the single arrays come from a database and I won't add a $datearray[4], $datearray[5] and so on, everytime there is a new entry in the mySQL..

The result of print_r($datearray):

Array ( 
    [0] => Array ( [0] => 2014-03-08 ) 
    [1] => Array ( [0] => 2013-09-15 ) 
    [2] => Array ( [0] => 2013-09-21 ) 
    [3] => Array ( [0] => 2013-10-03 
                   [1] => 2013-10-04 
                   [2] => 2013-10-05 
                   [3] => 2013-10-06 )
      )  
  • 写回答

2条回答 默认 最新

  • dragoninasia2014 2013-09-11 01:52
    关注

    What you might be looking for is to flatten the array:

    $datesarray = call_user_func_array('array_merge', $datearray);
    

    It's identical to how you were manually merging together the array items.

    See also: call_user_func_array()

    You could also do this inside the loop with a simple loop:

    $datesarray = array();
    
    while ($row = mysql_fetch_row($sql1)) {
        // ...
        foreach (createDateRangeArray($startzeit_format,$endzeit_format) as $item) {
            $datesarray[] = $item;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C