Notice: Undefined offset searching inside array com for

Asked

Viewed 967 times

2

Hello!

My code is a schedule and works as follows, there is an array with some times inside:

$horarios = ["08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"];

I then make a SELECT in the database looking for schedules and store the data inside an array through a foreach:

$stmt = $dbh->query("SELECT *, date_format(hora_agendamento, '%H%:%i') as hora_agendamento FROM agendamentos WHERE data_agendamento='$data_agendamento_convert' AND medico='$medico_completo'");
  $result = $stmt->fetchAll();

After that I walk through an array and check if each time of the $hours array can be found within the $result array:

for ($i=0; $i <= (count($horarios) - 1); $i++) {
  if (in_array($horarios[$i], $result[$i])) { ?>
    <tr>
      <td><?php echo $horarios[$i]; ?></td>
      <td><?php echo $result[$i]['nome']; ?></td>
      <td><?php echo $result[$i]['descricao']; ?></td>
      <td>Editar</td>
    </tr>
 <?php } else { ?>
    <tr>
       <td><?php echo $horarios[$i]; ?></td>
       <td></td>
       <td></td>
       <td>Editar</td>
     </tr>
 <?php } }?>

The first line found is printed correctly, then I believe that because it has 10 times in $hours and only 3 times in $result the code starts to return me the error below:

Notice: Undefined offset: 3 in C: wamp64 www admin agenda1.php on line 91

I imagine that if I improve this my if I can solve the problem, but I’m not sure what to use to improve it, someone can give me a light?

Thank you!

  • If code can contain problems even in the elaboration, why, fetchAll() does not already return an array ? to do a for? which is line 96?

  • Yes, it does, but I need to use this data outside of foreach, so I fed another array with the data that SELECT returns. Line 96: if (in_array($horarios[$i], $agendamentos[$i])) { ?>

  • 1

    No need to generate the data if you have the data!? understands this. the variable result is the same thing as the variable schedules

  • Wow, correct, my haha fails, but the Undefined offset problem persists, because the content of the two arrays (scheduling and result) are the same.

  • 1

    Here’s the next problem: if (in_array($horarios[$i], $result[$i])) { ?> because the result[$i] you are accessing the log and not the array you need, if you need to compare schedules you have to have another strategy. What is the purpose of this part?

  • In this part I want to know if there are schedules for the schedules contained in the $horarios array, so I made a condition for when I find an equal record he show me in the table the data of that schedule, patient name and schedule description, If you don’t find anything it executes Else and completes the table with empty data.

  • Good come on! why know the result if SQL brings what has? not just print $result? Why compare if you need to show ? think a little! tip takes this check and has print on screen!

  • 1

    This way he prints the lines right one after the other, but now I need him to check the schedule and fill in the correct line, so there was that if, for when you match between the time of $hours and the time of the $result it fill that line with the data, when not this match, ran the Else and filled the blank line, so I had view of the agenda with all the times used and available too, this is the idea.

  • 1

    So do it like this: if (in_array($result[$i]['hora_agendamento'], $horarios)) { ?> that is, just invert the variables within the function in_array

  • You are taking the data, just keep giving Undefined offset 3, because it has few results, it goes from 0 to 2 only(3 records found in the database), I need to stop iterating $result because at some point I happen to be wanting data from a non-existent offset inside the array and generates the error, I need a better if.

Show 5 more comments

1 answer

2


Do it:

if (isset($result[$i]) && in_array($result[$i], $horarios)) { ?>

So this error will stop appearing because the isset($result[$i]) checks if THERE is the variable with the index in array $result. Who will return true if such a value exists and provided that it is not null.

$array = array(0 => "oi", 1 => "", 2 => null, 3 => false);

isset( $array [0] ) // true
isset( $array [1] ) // true
isset( $array [2] ) // false
isset( $array [3] ) // true

In addition, as quoted by Virgilio Novic in the comments, the right is:

in_array ("valor que eu procuro", array());

View documentation

Therefore, you need to put the $result[$i] before $horarios. Like $horarios is already an array(), you do not need to indicate an index in $horarios.

EDIT

As the image shown, you can make a loop inside your loop, to analyze each case. See:

for($i = 0; $i < count($horarios); $i++){
    $status = true;
    foreach($result as $resultado){
        if($horarios[$i] == $resultado['hora_agendamento']){
        ?>
            <tr>
              <td><?php echo $horarios[$i]; ?></td>
              <td><?php echo $resultado['nome']; ?></td>
              <td><?php echo $resultado['descricao']; ?></td>
              <td>Editar</td>
            </tr>
        <?php 
            $status = false;
            break;
        }
    }
    if($status){ ?>

    <tr>
       <td><?php echo $horarios[$i]; ?></td>
       <td></td>
       <td></td>
       <td>Editar</td>
     </tr>

<?php }}?>

EDIT 2

Although the other way meet, this example below, with array_search is more optimized.

$horariosCheios = array();
foreach($result as $resultado){
    $horariosCheios[] = $resultado['hora_agendamento'];
}

for ($i=0; $i <= (count($horarios) - 1); $i++) {
  if (($indice = array_search($horarios[$i], $horariosCheios)) !== false) { ?>
    <tr>
      <td><?php echo $horarios[$i]; ?></td>
      <td><?php echo $result[$indice]['nome']; ?></td>
      <td><?php echo $result[$indice]['descricao']; ?></td>
      <td>Editar</td>
    </tr>
 <?php } else { ?>
    <tr>
       <td><?php echo $horarios[$i]; ?></td>
       <td></td>
       <td></td>
       <td>Editar</td>
     </tr>
 <?php } }?>
  • I understand, but a problem arises, if with the if I search for the content of $result within $hours will end up displaying to me first the 3 results found, after the ones that fell in Else, as seen in the image below, I will think of something to circumvent: https://imgur.com/a/xCCIvrN

  • @Fernandogross try now.

  • 1

    Ball show, could not have worked out more right, I was doing something of the genre but half skeptical, I’m always afraid to accumulate many loops, but it worked perfectly, thank you, besides the code I took valuable tips, both your @Andrei Coelho and Virgilio Novic.

  • 1

    @Fernandogross I gave this suggestion but it should not be the best. This is just one example, because depending on the amount you will make many unnecessary loops perhaps. You need to then refactor this code and do some tests. Also search on array_search. It can help you more. Hug!

  • 1

    @Fernandogross put Edit 2 as a better example.

  • 1

    Great! When I was looking for which function to use to search the schedules inside the array I bumped into this function there in the documentation, but I didn’t get to test it, the principle is very similar.

  • @Fernandogross yes. And it looks more like what you did in your first code.

Show 2 more comments

Browser other questions tagged

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