Optimize code to eliminate array value

0

I have this code:

//empezamos con articulos
    $ConsArticulos = Consulta_Dinamica("Array","id,color","Articulos","(FIND_IN_SET ('".$_SESSION["Empresa_Id"]."', 'empresa')) AND (FIND_IN_SET ('".$_POST["ReasViejoColor"]."', 'color'))");
    foreach($ConsArticulos as $Darticulos) { 
    $Articulosviej = explode(',',$Darticulos["color"]);
for ($i=0;$i<count($Articulosviej);$i++) { if ($Articulosviej[$i] == $_POST["ReasViejoColor"]) { $Articulosviej[$i] = $_POST["ReasNuevoColor"]; } }
    $Articulosviej = implode(",", $Articulosviej);
    $UpArtiColor = Actualizar_Datos("Articulos" , "'color' = '".$Articulosviej."' " ,"id","".$Darticulos["id"]."");
} //fin de articulos

What it does is delete a value from one array and replace it with another. Running works but I have a feeling that it is a very dirty code and that there must be some function that does this directly.

The value to replace the array comes from a mysql field that is separated by ,

the array that brings me the first query is this:

Array
(
    [0] => Array
        (
            [id] => 165
            [color] => 301,304,303,300
        )

)

in this case it only has one value, but it is normal to have several, in some cases color only has one value, but it mostly has several.

The thing would be to read that array and replace one of the values with a new one, as I do in the for of my code.

I had tried with an array replace but I have not been able to start it.

    
asked by Killpe 04.12.2017 в 21:28
source

1 answer

1

You do not need the for loop. str_replace can work perfectly with arrays:

$Articulosviej = explode(',', $Darticulos["color"]);
$Articulosviej = str_replace($_POST["ReasViejoColor"], $_POST["ReasNuevoColor"], $Articulosviej);
$Articulosviej = implode(',', $Articulosviej);

Fiddle

    
answered by 04.12.2017 / 23:45
source