Php数组替换0和00

时间:2016-06-30 10:54:29

标签: php arrays

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

$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",
]

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

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

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

被告知

sprintf()

答案 1 :(得分:0)

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)

答案 2 :(得分:0)

为什么不在循环中使用替换? 这里:

<?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);

答案 3 :(得分:0)

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

<?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);