1

I have a variable array that looks like this when 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)

Since I dont know how many of these elements will be in the array and I will merge it later with other arrays, I want it to look like this:

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)

And this should go on obviously for other elements, date_from_2, date_to_2, ...

2
  • Any time you find yourself creating variables or properties with numbered names like that, you should be using an array instead. Commented Aug 27, 2016 at 9:08
  • Why are you merging those two entries? They have different vacancy_id. Which vacancy_id should be used in the combined object? Commented Aug 27, 2016 at 9:09

1 Answer 1

1

Actually it's pretty easy

$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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.