遍历数组并根据特定字符串是否在数组中采取操作';s指数


Stepping through an array and taking actions depending on if certain strings are in the array's indeces

所以我有一个外部文本文件,大约有20行文本。我想做的是将每一行文本放入数组中的索引中。没关系。

现在我遇到了一些麻烦。我需要遍历数组,并根据索引中是否有某个字符串来执行操作。

每个索引的格式为:"add xxxx"、"next"或"remove xxxx",其中xxxx是一个在数组中只使用一次的名称。

在这种情况下,如果其中有一个索引为"add",我需要将不带"add"的索引推送到一个新数组中。如果它有"next",我需要将第一个索引从新数组中移出,并记录移出的索引。最后,如果索引中有"remove",我需要搜索并删除任何包含"xxxx"名称的索引。

<?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);    
?>

我真正的问题是,在逐个键的基础上逐步遍历数组,然后相应地执行操作的最佳方法是什么?

foreach($array as $key => $value ) {
  if(shouldActOn($key)) {
    // your code goes here.
  }
}