我正在尝试使用数组编写一个 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 条目一个。有人可以让我知道我做错了什么吗?谢谢。
冉冉说