Php阵列替换0 wth 00


Php array replace 0 wth 00

我有一个数组,它看起来像这样:

$a = [
  0 => "0",
  1 => "01",
  2 => "00",
]

我想用两个零代替一个零。

应该是这样的:

[
  0 => "00",
  1 => "01",
  2 => "00",
]

我做到了:

$newDigit = str_replace("0", "00", $splitDigit);

但它在所有地方都加了2个零:

[
  0 => "000",
  1 => "0001",
  2 => "0000",
]

我该如何解决此问题?

foreach($arr as $str)
    $str = preg_replace('/^(0)$/', '00', $str);

foreach($arr as $str)
    if($str === '0')
            $str = '00';

CCD_ 1。

sprintf()是您的朋友:

$array = ["0", "01", "02"];
function doubleO($v){
    return(sprintf("%02d",$v));
}
$array = array_map("doubleO",$array);
print_r($array);

输出:

阵列([0]=>00[1]=>01[2]=>02(

为什么不在一个简单的循环中进行替换?

<?php
        $arrDigits = [
                               0 => "0"
                               1 => "01"
                               2 => "00"
                              ];
        foreach($arrDigits as $key=>$strDigit){
            If ($strDigit == "0"){
                 $arrDigit[$key] = str_replace("0", "00", $strDigit);
            }
        }
        var_dump($arrDigits);

为什么不在循环中使用do替换?此处:

<?php
        $arrDigits = [
                               0 => "0"
                               1 => "01"
                               2 => "00"
                              ];
        foreach($arrDigits as $key=>$strDigit){
            If ($strDigit == "0"){
                 $arrDigit[$key] = str_replace("0", "00", $strDigit);
            }
        }
        var_dump($arrDigits);