[英]Replacing a substring with values from an array in 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條目一個。 有人可以讓我知道我在做什么錯嗎? 謝謝。
不要手動創建JSON。 循環構建數組,並在最終結果上使用json_encode()
。 您可以在循環期間從數組中獲取十六進制代碼,而不是隨后進行數百次字符串替換。
要格式化數組鍵,可以使用sprintf()
連接所有片段,並在$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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.