我正在尝试找到最有效的方法来获取数组中的每个第五项,然后使用str_replace修改它。
例如,每隔五个项目修改[3r]至[4r]。
$ myArray = array(“apples [3r]”,“jacobs [3r]”,“chocolate [3r]”,“makeup [3r]”,“lipstick [3r]”,“triangle [3r]”, “jacobson [3r]”,“lacksasf [3r]”,“dahe [3r]”,“applestoapples [3r]”,“coaxale [3r]”,“hamburger [3r]”,“前缀[3r]”
这是输出
苹果[3r] jacobs [3r]巧克力[3r]化妆[3r]唇膏[4r]三角形[3r] jacobson [3r] lacksasf [3r] dahe [3r] applestoapples [4r] coaxale [3r] hamburger [3r] ]前缀[3r]
答案 0 :(得分:5)
使用“for”从4开始(数组的第5个元素)并逐步增加5个:
for ($i = 4; $i < count($myArray); $i += 5) {
$myArray[$i] = str_replace('[3r]', '[4r]', $myArray[$i]);
}
编辑:我忘了再次将结果分配给数组。
答案 1 :(得分:3)
for ($i = 0; $i*5+4 < sizeof($myArray); $i++) {
$myArray[$i*5+4] = str_replace("[3r]","[4r]", $myArray[$i*5+4]);
}
答案 2 :(得分:1)
for( $i=0;$i<count( $array );$i+=<N-1> ){
...
}
使用for循环并每次添加N-1
答案 3 :(得分:1)
$myArray = array("apples[3r]", "jacobs[3r]", "chocolate[3r]", "makeup[3r]", "lipstick[3r]", "triangle[3r]", "jacobson[3r]", "lacksasf[3r]","dahe[3r]", "applestoapples[3r]", "coaxale[3r]", "hamburger[3r]", "prefix[3r]");
$len = count($myArray);
$total = floor($len/5);
$count = 5;
for($i=0, $i<= $total, $i++) {
$myArray[$count] = str_replace("[3r]", "[4r]", $myArray[$count]);
$count += 5;
}
答案 4 :(得分:1)
只是迭代你的数组但只改变每个fith项:
$i = 0;
foreach ($myArray as &$value)
{
if ($i++ % 5) continue;
$value = str_replace(/* lookup the manual if you don't know this function */);
}
unset($value);
如果您不想在0
使用$i
初始化-4
时开始统计。
答案 5 :(得分:0)
这将进行此更改:
$myArray = array(
"apples[3r]",
"jacobs[3r]",
"chocolate[3r]",
"makeup[3r]",
"lipstick[3r]",
"triangle[3r]",
"jacobson[3r]",
"lacksasf[3r]",
"dahe[3r]",
"applestoapples[3r]",
"coaxale[3r]",
"hamburger[3r]",
"prefix[3r]"
);
$sizeMyArray = count($myArray);
for ($i = 4; $i < $sizeMyArray; $i+= 5) {
$myArray[$i] = str_replace('[3r]', '[4r]', $myArray[$i]);
}
print_r($myArray);
/* Array (
* [0] => apples[3r]
* [1] => jacobs[3r]
* [2] => chocolate[3r]
* [3] => makeup[3r]
* [4] => lipstick[4r]
* [5] => triangle[3r]
* [6] => jacobson[3r]
* [7] => lacksasf[3r]
* [8] => dahe[3r]
* [9] => applestoapples[4r]
* [10] => coaxale[3r]
* [11] => hamburger[3r]
* [12] => prefix[3r] ) */