» Opening a File Into a Multi-Dimensional Array by falsepride |
|
(Login to remove green text ads)
In the following examples, I will show you how to open a file with two "safe characters" into a multidemsional array.
PHP Code:
function readintomdarray($filename, $safecharacter1, $safecharacter2) {
$mdarray = array();
$file = file($filename);
foreach($file as $line) {
$line = trim($line);
$final .= "$line";
}
$temp = explode($safecharacter1, $final);
array_pop($temp);
$length = count($temp);
for ($i = 0; $i < $length; $i++) {
$mdarray[$i] = array();
$temp2 = explode($safecharacter2, $temp[$i]);
$length2 = count($temp2);
for ($i2 = 0; $i2 < $length2; $i2++) {
$mdarray[$i][$i2] = $temp2[$i2];
}
}
return $mdarray;
}
Now lets break that down step by step.
PHP Code:
//creates an array
$mdarray = array();
//opens the file into one string, with no linebreaks, linebreaks can cause problems when retrieving stored data
$file = file($filename);
foreach($file as $line) {
$line = trim($line);
$final .= "$line";
}
//$temp becomes an array
$temp = explode($safecharacter1, $final);
//pops the last array value off(this part isn't needed if you're file doesnt end with you're $safecharacter1)
array_pop($temp);
//$length becomes a number for the number of second layer arrays we need
$length = count($temp);
//cycles through the number of second layer arrays
for ($i = 0; $i < $length; $i++) {
//creats second layer array
$mdarray[$i] = array();
//$temps becomes an array with all the values for one second layer array
$temp2 = explode($safecharacter2, $temp[$i]);
//
$length2 = count($temp2);
//$length becomes a number for the number of second layer array values we need
//cycles through second layer arrays values
for ($i2 = 0; $i2 < $length2; $i2++) {
//assigns second layer array values
$mdarray[$i][$i2] = $temp2[$i2];
//return the multi-dimensional array
return $mdarray;
This function can be used for setting up a php news system, or other things of that nature. For the safe characters I normally use |<| and |>|, but you can use what ever you want as long as you're sure it won't be in your strings.
|
|