Invalid argument supplied for foreach() + Logic of

2020-05-05 17:42发布

I posted a similar question earlier today, however I recently downloaded xampp and can now get syntax errors. I'm very new to all of this.

Please see this example to see the current state of my .php file: http://rich2233.comoj.com/file2.php

I can get the .txt file to extract and display the content from the .txt file, but any attempt of modifying the .txt file does not happen.

When I ran this on xampp, I got this error: Invalid argument supplied for foreach() in file2.php on line 30

标签: php
4条回答
贼婆χ
2楼-- · 2020-05-05 18:01

Try:

$users = file($filename);

I suspect $users === false as you aren't using the same "calculated" file name.

查看更多
够拽才男人
3楼-- · 2020-05-05 18:09

Here's a quick tip: keep track of your iterator. Confusing? Think of each row number as unique offset in the file. You need to iterate (foreach) and increment it by +1 each time. When you're editing a row later on, you just need to submit the offset number, iterate again and check if $i == $_POST['iterator'].

// Iterator example
$users = file('text.txt');
$hours_taken = array();

foreach ($users as $user) {
  list($time, $name) = explode('|', $user);
  array_push($hours_taken, $time);
}
// Assuming same order of rows in users.txt
$hours = array('8:00 am', '9:00 am', '10:00 am'); // ...5:00 pm
$i = 1;
echo '<select name="time"><option selected>-- Select time --</option>';
foreach ($hours as $hour) {
  if (in_array($hour, $hours_taken)) {
    echo '<option disabled=disabled>'. $hour .'</option>';
  }
  else {
    echo '<option value='. $i .'>'. $hour .'</option>';
  }
  $i++;
}
查看更多
叛逆
4楼-- · 2020-05-05 18:13

After your most recent update of the code: The answer to the error message in the question title is:

The code is missing the line $users = file("test.txt");

查看更多
叛逆
5楼-- · 2020-05-05 18:18

Edited as that last function wouldn't have worked

function editTxt(){
  $find_name = $_POST['name'];
  $find_time = $_POST['time'];
  $filename = getcwd() . "/test.txt";
  $lines = file( $filename , FILE_IGNORE_NEW_LINES );
  foreach($lines as $key => $line)
  {
      list($time, $name) = explode('|', $line);
      if($time == $find_time && $name == "Available")
      {
          $lines[$key] = $time."|".$find_name;
          file_put_contents( $filename , $lines );
          break;
      }
  }
}

If you are planning to use this for something other than just an exercise I suggest using a database.

查看更多
登录 后发表回答