Last active
April 2, 2021 15:16
-
-
Save molotovbliss/033ba2d8c69d932a11e6 to your computer and use it in GitHub Desktop.
Simple PHP Class to save an array to disk and read it back into a PHP Array using JSON.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Save an PHP Array to disk with a delimiter to support | |
* multiple array values. Associative Array supported. | |
* | |
* @author Jared Blalock (jared.blalock@gmail.com) | |
* @link http://molotovbliss.com | |
*/ | |
Class Json_Array { | |
/** | |
* Save array to Disk via JSON with delimiter | |
* | |
* @param string $file | |
* @param array $data | |
* @param string $delimiter | |
* @return boolean | |
*/ | |
public function saveArray($file, $data, $delimiter = '|') { | |
$save = file_put_contents($file, json_encode($data).$delimiter, FILE_APPEND); | |
if($save === FALSE) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
/** | |
* Read saved aray back to PHP via JSON | |
* | |
* @param string $file | |
* @param string $delimiter | |
* @param boolean $returnAsArray | |
* @return array|boolean $output | |
*/ | |
public function loadArray($file, $delimiter = '|', $returnAsArray = true) { | |
$data = explode($delimiter, file_get_contents($file)); | |
if($data === FALSE) { | |
return false; | |
} else { | |
foreach($data as $d) { | |
$output[] = json_decode($d, $returnAsArray); | |
} | |
return array_pop($output); | |
} | |
} | |
} | |
/** | |
* EXAMPLE USAGE OF CLASS | |
*/ | |
// Example Array | |
$testArray = array("Volvo", "BMW", "Toyota"); | |
$testArray[] = "Dodge"; | |
// Filename to save array data to | |
$filename = 'testarray.json'; | |
// Array to store read of saved data | |
$dataFromDisk = array(); | |
// Create Class Object | |
$jsonArray = new Json_Array; | |
// Save test array to disk | |
$jsonArray->saveArray($filename, $testArray); | |
// Read test array from disk | |
$dataFromDisk = $jsonArray->loadArray($filename); | |
// Output contents | |
if(!$dataFromDisk) { | |
echo "Data not found."; | |
} else { | |
print_r($dataFromDisk); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment