要将数组值替换为0,不包括工作和家庭
array(work,home,sky,door);
我想用php替换这个数组值,
我试着用这个函数来替换这个数组
$asting = array(work,home,sky,door);
$a = str_replace("work","0",$asting);
如果我从提交的表单中添加的数组是无穷大,但我想将值替换为0,而不包括工作和家庭,情况会怎样?
发布于 2011-03-04 10:14:40
这是我的最终代码
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;
发布于 2012-11-14 02:30:05
一个更优雅和更短的解决方案。
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
&运算符是指向数组中特定原始字符串的指针。(而不是该字符串的副本),您可以通过这种方式为数组中的字符串分配一个新值。唯一不能做的事情是任何可能扰乱数组顺序的事情,比如unset()或键操作。
上述示例的结果数组将为
$aArray = array('work','home', 0, 0)
发布于 2011-03-03 19:12:32
循环将多次执行一系列操作。因此,对于数组中的每个元素,您将检查它是否等于您想要更改的元素,如果是,则更改它。另外,一定要在字符串两边加上引号
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
以下是一些建议阅读:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
但是,如果您正在为诸如循环之类的东西而苦苦挣扎,那么您可能需要阅读一些入门编程材料。这应该能帮助你真正理解到底发生了什么。
https://stackoverflow.com/questions/5179606
复制相似问题