Advertisement
jargon

optimize.php

Jul 28th, 2024 (edited)
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.16 KB | None | 0 0
  1. <?php
  2.  
  3. function cleanKeys($obj, $debug = false) {
  4.    
  5.     $cleanedObj = [];
  6.  
  7.     foreach ($obj as $key => $value) {
  8.        
  9.         $cleanKey = $key;
  10.         $cleanValue = $value;
  11.  
  12.         // Reassign numeric string keys as float type
  13.         if (is_string($cleanKey) && strval(floatval($cleanKey)) === $cleanKey) {
  14.             $cleanKey = floatval($cleanKey);
  15.         }
  16.        
  17.         // Reassign numeric string values as float type
  18.         if (is_string($cleanValue) && strval(floatval($cleanValue)) === $cleanValue) {
  19.             $cleanValue = floatval($cleanValue);
  20.         }
  21.  
  22.         if (is_string($cleanValue)) {
  23.             // Replace escaped slashes with regular slashes
  24.             $cleanValue = str_replace('\/', '/', $cleanValue);
  25.             // Remove escaped double quotes from the value
  26.             $cleanValue = str_replace('\"', '', $cleanValue);
  27.         }
  28.  
  29.         // Add spaces inside double curly braces if the content doesn't start or end with whitespace
  30.         if (is_string($cleanValue)) {
  31.             if (preg_match_all("/{{(?<inner>[^\s].+[^\s])}}/", $cleanValue, $matches, PREG_SET_ORDER) > 0) {
  32.                 foreach ($matches as $match) {
  33.                     $cleanValue = str_replace($match[0], "{{ " . strtolower($match['inner']) . " }}", $cleanValue);
  34.                 }
  35.             }
  36.         }
  37.  
  38.         // Assign the cleaned key and value
  39.         $cleanedObj[$cleanKey] = $cleanValue;
  40.     }
  41.  
  42.     // Extract keys and sort them naturally
  43.     $keys = array_keys($cleanedObj);
  44.     natcasesort($keys);
  45.  
  46.     // Rebuild the array with sorted keys
  47.     $sortedObj = [];
  48.     foreach ($keys as $key) {
  49.         $sortedObj[$key] = $cleanedObj[$key];
  50.     }
  51.  
  52.     if ($debug) {
  53.         var_dump($sortedObj);
  54.     }
  55.  
  56.     return $sortedObj;
  57. }
  58.  
  59. $items = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/Story05Js dictionary/assets/books/Book Puzzlum's Palace 0.json"), true);
  60.  
  61. $cleanedItems = cleanKeys($items, true);
  62. print_r($cleanedItems);
  63.  
  64. file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/Story05Js dictionary/assets/books/Book Puzzlum's Palace Optimized 2.json", json_encode($cleanedItems, JSON_PRETTY_PRINT));
  65.  
  66. exit;
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement