0

So I've got an external text file with about 20 lines of text. What I'm trying to do is get each line of text into an index in an array. That's fine.

Now where I'm running into some trouble. I need to step through the array, and depending on if the index has a certain string in it, carry out an action.

Each index will either be formatted as: "add xxxx", "next" or "remove xxxx", where xxxx is a name that will only be used once in the array.

In this case, if an index as "add" in it, I need to push that index sans the "add " to a new array. If it has "next" in it, I need to shift the first index out of the new array, and log whatever index was shifted out. Finally, if "remove" is in the index, I need to search and remove whatever index contains the "xxxx" name.

<?php
$fileContent = file_get_contents("queueList.txt");
$queueList = (explode("\n", $fileContent));
$newArray = array();

foreach($queueList as $command){
if($n = strstr($command, "add")) {
  array_push($newArray, $n);
    }

else if($x = strstr($command, "next")) {
  // need to print the index before pushing out
  array_push($newArray, $x);     
    }

else if($z = strstr($command, "remove")) {  
unset($newArray[$z]);
    }

  };//end foreach
print_r ($newArray);    
?>

My real question is, what's the best way to step through an array on a key by key basis, and then carry out an action accordingly?

4

1 回答 1

1
foreach($array as $key => $value ) {
  if(shouldActOn($key)) {
    // your code goes here.
  }
}
于 2013-09-02T02:04:39.137 回答