Avoiding arrays as values when using array_merge_recursive()

Asked

Viewed 17 times

0

I have the following array:

$vagas = array(
  '2017-09-22' => array(
    '11:30' => 2,
    '12:00' => 3,
    '15:00' => 1
  ),
  '2017-09-23' => array(
    '9:00' => 5,
    '10:00' => 3,
    '11:30' => 2
  )
);

This array is updated through a form, where the user can enter multiple dates, times and number of vacancies for the chosen times.

$vacancy_days = array_filter($_POST['vacancy-days']);
$vacancy_number = wp_strip_all_tags($_POST['vacancy-number']);
$vacancy_number = intval($vacancy_number);
$vacancy_hours = array_filter($_POST['vacancy-hours']);

$created_vacancies = array();
foreach ($vacancy_days as $day) {
  foreach ($vacancy_hours as $hour) {
    $created_vacancies[$day][$hour] = $vacancy_number;
  }
}

At the end, merge with the existing array:

$vacancies = get_option('vagas');
$new_vacancies = array_merge_recursive($vacancies, $created_vacancies);
update_option('vagas', $new_vacancies);

The array_merge_recursive() works well, including including new timetables on existing dates. The problem happens when I report an existing schedule on an existing date. In this case, it creates an array to store the two vacancy numbers (old and new).

How do I resolve this? Keep only the number of new vacancies.

  • In case, if the user informed the date 2017-09-23, 9:00h, 1 wave, the value 5 should be replaced by 1?

  • @Andersoncarloswoss That’s right. At the moment, he create an array with the two values.

1 answer

1

Solved:

$vacancies = get_option('vagas');
$new_vacancies = array_merge_recursive($vacancies, $created_vacancies);

foreach($new_vacancies as $key => $vaga){
foreach($vaga as $key2 => $horario){
  if(is_array($horario)){
    $last_value = end($horario);
    $new_vacancies[$key][$key2] = $last_value;
  }
}
}

update_option('vagas', $new_vacancies);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.