用PHP中数组中的值替换子字符串

我正在尝试使用数组编写一个 JSON 文件。最初,该文件用于在服务器上创建 colorbook.js 文件,然后手动查找和替换以将所有值塞入其中。这是代码:


<?php

$colorsperpage = 48; // format is 6 columns by 8 rows

$letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K');

$hexValues = array('ECECEC', 'D9D9D9', 'C7C7C7', 'B4B4B4', 'A2A2A2');


$txt = "var color = {\r\n";


for ($i = 0 ; $i < count($letters) ; $i++){

    $pagenum = $i + 1;

    for ( $j = 1; $j <= $colorsperpage; $j++ ){

        if ($j < 10){

            if ($j == $colorsperpage){

                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";

            } else {

                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";

            }

        } else {

            if ($j == $colorsperpage){

                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";

            } else {

                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";

            }


        }

    }

};



$txt .= "};";


foreach ($hexValues as $hex){

    $txt = preg_replace('/rgba(255,255,255,1)/', $hex, $txt, 1);

}

$jsonFile = fopen('colorbook.js', 'w') or die('Unable to open file!');

fwrite($jsonFile, $txt);

fclose($jsonFile);

?>

原始脚本确实正确地写入了文件(如果您删除了 foreach 循环)。我假设运行 preg_replace 会遍历该字符串,一次一个替换十六进制值。注意原始数组是 528 项;为了在这里发帖,我缩短了它。每个 RGBA 条目一个。有人可以让我知道我做错了什么吗?谢谢。


德玛西亚99
浏览 140回答 1
1回答

冉冉说

不要手动创建 JSON。在循环中构建数组,并json_encode()在最终结果上使用。您可以在循环期间从数组中获取十六进制代码,而不是之后进行数百次字符串替换。并且要格式化数组键,您可以使用sprintf()连接所有部分并为$j.<?php$result = [];$color_index = 0;foreach ($letters as $i => $letter) {&nbsp; &nbsp; $pagenum = $i + 1;&nbsp; &nbsp; for ($j = 1; $j <= $colorsperpage; $j++) {&nbsp; &nbsp; &nbsp; &nbsp; $key = sprintf("%s%d-%02d", $letter, $pagenum, $j);&nbsp; &nbsp; &nbsp; &nbsp; $colorcode = $hexValues[$color_index++];&nbsp; &nbsp; &nbsp; &nbsp; $result[$key] = $colorcode;&nbsp; &nbsp; }}file_put_contents("colorbook.js", "var color = " . json_encode($result));
打开App,查看更多内容
随时随地看视频慕课网APP