我想操纵数组元素。因此,如果某个数组元素以字母n
或m
结尾,并且以下元素例如是apple
,那么我想删除" a" " apple"所以我得到一个输出:Array ( [0] => man [1] => pple )
我的代码:
$input = array("man","apple");
$ending = array("m","n");
$example = array("apple","orange");
for($i=0;$i<count($input);$i++)
{
$second = isset( $input[$i+1])?$input[$i+1][0]:null;
$third = substr($input[$i],-2);
if( isset($third) && isset($second) ){
if ( in_array($third,$ending) && in_array($second,$example) ){
$input[$i+1] = substr($input[$i+1],0,-2);
}
}
}
如何更改代码以便获得所需的输出?
答案 0 :(得分:1)
听起来像是一项很酷的运动任务。
在阅读开始评论后,我的方法是这样的:
$input = ['man', 'hamster', 'apple', 'ham', 'red'];
$endings = ['m', 'n'];
$shouldRemove = false;
foreach ($input as $key => $word) {
// if this variable is true, it will remove the first character of the current word.
if ($shouldRemove === true) {
$input[$key] = substr($word, 1);
}
// we reset the flag
$shouldRemove = false;
// getting the last character from current word
$lastCharacterForCurrentWord = $word[strlen($word) - 1];
if (in_array($lastCharacterForCurrentWord, $endings)) {
// if the last character of the word is one of the flagged characters,
// we set the flag to true, so that in the next word, we will remove
// the first character.
$shouldRemove = true;
}
}
var_dump($input);
die();
此脚本的输出为
array(5) { [0]=> string(3) "man" [1]=> string(6) "amster" [2]=> string(5) "apple" [3]=> string(3) "ham" [4]=> string(2) "ed" }
我希望对评论的解释是足够的。