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.
str_replace().