合并其他数组中的某些数组元素并更改键名

时间:2016-08-27 09:01:42

标签: php arrays

我有一个变量数组,在var_dumped:

时看起来像这样
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,...

显然应该继续

1 个答案:

答案 0 :(得分:1)

实际上它非常简单

$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++;
}