简体   繁体   中英

Replacing a substring with values from an array in PHP

I am trying to write a JSON file using arrays. Originally, the file was used to create a colorbook.js file on the server and then a manual find and replace to handjam all the values into it. This is the code:

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

The original script did write the file correctly(if you remove the foreach loop). I assumed that running preg_replace would go through that string and one at a time replace the hex values. Note that the original array is 528 items; I shortened it for the sake of posting here. One for each of the RGBA entries. Could someone let me know what I'm doing wrong? Thanks.

Don't create JSON by hand. Build the array in a loop, and use json_encode() on the final result. You can get the hex codes from the array during the loop, rather than doing hundreds of string replacements afterward.

And to format the array keys, you can use sprintf() to concatenate all the pieces and give a leading zero to $j .

<?php
$result = [];
$color_index = 0;
foreach ($letters as $i => $letter) {
    $pagenum = $i + 1;
    for ($j = 1; $j <= $colorsperpage; $j++) {
        $key = sprintf("%s%d-%02d", $letter, $pagenum, $j);
        $colorcode = $hexValues[$color_index++];
        $result[$key] = $colorcode;
    }
}
file_put_contents("colorbook.js", "var color = " . json_encode($result));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM