将一些数组元素合并到其他数组中,并更改键名


Merge some array elements in other array and change key name

我有一个变量数组,当var_dump:

array (size=2)
  0 => 
    object(stdClass)[31]
      public 'vacancy_calendar_id' => string '1' (length=1)
      public 'vacancy_id' => string '1' (length=1)
      public 'date_from' => string '2016-08-25 00:00:00' (length=19)
      public 'date_to' => string '2016-08-27 00:00:00' (length=19)
  1 => 
    object(stdClass)[30]
      public 'vacancy_calendar_id' => string '5' (length=1)
      public 'vacancy_id' => string '1' (length=1)
      public 'date_from' => string '2016-08-30 00:00:00' (length=19)
      public 'date_to' => string '2016-08-30 00:00:00' (length=19)

由于我不知道数组中有多少元素,并且我稍后会将其与其他数组合并,因此我希望它看起来像这样:

array (size=2)
      0 => 
        object(stdClass)[31]
          public 'vacancy_calendar_id' => string '1' (length=1)
          public 'vacancy_id' => string '1' (length=1)
          public 'date_from_0' => string '2016-08-25 00:00:00' (length=19)
          public 'date_to_0' => string '2016-08-27 00:00:00' (length=19)
          public 'date_from_1' => string '2016-08-30 00:00:00' (length=19)
          public 'date_to_1' => string '2016-08-30 00:00:00' (length=19)

对于其他元素,date_from_2, date_to_2,…

其实很简单

$merged = new stdClass;
$merged->vacancy_id = $data[0]->vacancy_id;
$i = 0;
foreach( $data as $row ){
    $merged->{'date_from_'.$i} = $row->date_from;
    $merged->{'date_to_'.$i} = $row->date_to;
    $i++;
}