2011-03-03 9 views
9

desea reemplazar el valor de la matriz con 0, excluir el trabajo y el hogarphp - reemplace valor de matriz

array(work,home,sky,door); 

quiero usar PHP para sustituir este valor de matriz,

tengo trate de usar esta función para reemplazar esta gama

$asting = array(work,home,sky,door); 
$a = str_replace("work","0",$asting); 

¿qué hay de mi matriz es infinito para agregar desde el formulario enviado, pero quiero reemplazar el valor a 0 excluye el trabajo a casa & solamente?

+0

Así que desea reemplazar 'door' y' 'sky' con 0'? ¿Los desarmó? – alexn

+0

sí, quiero reemplazar la puerta y el cielo con 0. – wyman

+0

¿Tiene una idea de la diferencia entre 'work' y' 'work''? Por favor, cite sus cadenas. – deceze

Respuesta

-1

esta mi código final

//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; 
10

Un ciclo realizará una serie de acciones muchas veces. Por lo tanto, para cada elemento de su matriz, debe verificar si es igual a la que desea cambiar y, si lo está, cambiarla. También asegúrese de poner comillas alrededor de sus cadenas

//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; 
} 

Aquí es un poco de lectura sugerido:

http://www.php.net/manual/en/language.types.array.php

http://www.php.net/manual/en/language.control-structures.php

Pero si usted está luchando en cosas tales como un bucle, es posible quiero leer algo de material introductorio de programación. Lo cual debería ayudarlo a comprender realmente lo que está pasando.

+0

Desea hacer '$ asting [$ i] = 0;'. – alexn

+0

finalmente mi script ya funciona, gracias a Jonno – wyman

1

También puede dar matriz como parámetro 1 y 2 en str_replace ...

+0

¿qué tal mi matriz es infinita para agregar desde el formulario enviado, pero quiero reemplazar el valor a 0 excluir el trabajo y el hogar solamente? – wyman

1

Sólo un pequeño punto en el bucle. Muchos no se dan cuenta de que la segunda tarea de comparación se realiza cada iteración nueva. Así que si se trataba de un caso de gran matriz o cálculo que podría optimizar bucle un poco haciendo:

for ($i = 0, $c = count($asting); $i < $c; $i++) {...} 

También puede querer ver http://php.net/manual/en/function.array-replace.php para el problema original a menos que el código realmente es final :)

+0

Pero array_replace busca "valores con las mismas claves" – AdamS

9

Un Un poco más elegante y una solución más corta.

$aArray = array('work','home','sky','door'); 

foreach($aArray as &$sValue) 
{ 
    if ($sValue!='work' && $sValue!='home') $sValue=0; 
} 

El operador & es un puntero a la cadena original en particular en la matriz. (en lugar de una copia de esa cadena) Puede asignar un nuevo valor a la cadena en la matriz. Lo único que no puede hacer es alterar el orden en la matriz, como unset() o manipulación de teclas.

La matriz resultante del ejemplo anterior será

$aArray = array('work','home', 0, 0) 
2

Un poco sí y de manera mucho más rápida, pero cierto, la necesidad de un bucle:

salida
//Setup the array of string 
    $asting = array('bar', 'market', 'work', 'home', 'sky', 'door'); 

//Setup the array of replacings 
    $replace = array('home', 'work'); 

//Loop them through str_replace() replacing with 0 or any other value... 
    foreach ($replace as $val) $asting = str_replace($val, 0, $asting); 

//See what results brings:  
    print_r ($asting); 

Will:

Array 
(
    [0] => bar 
    [1] => market 
    [2] => 0 
    [3] => 0 
    [4] => sky 
    [5] => door 
) 
+0

¿No se puede buscar strsea dentro de cada cadena? Por lo tanto, también reemplazaría "trabajo duro" y "alojamiento en familia" con 0. – AdamS

1

Una alternativa usando array_map:

$original = array('work','home','sky','door'); 

$mapped = array_map(function($i){ 
    $exclude = array('work','home'); 
    return in_array($i, $exclude) ? 0 : $i; 
}, $original); 
1

puede intentar array_walk función:

function zeros(&$value) 
{ 
    if ($value != 'home' && $value != 'work'){$value = 0;}  
} 

$asting = array('work','home','sky','door','march'); 

array_walk($asting, 'zeros'); 
print_r($asting); 
Cuestiones relacionadas