I'm trying to work out how it's best to split down some data I have. Whether into multiple separate arrays, or nested arrays, or something different.
I have a file that holds titles, filenames and dates for a number of different items. Each item is separated with the character ^
, and each part of the list is separated with a tilde ~
The file looks something like this:
Example post one~example-post-one~Friday 17 October 2014^
Wayfinding For The Mobile Web~wayfinding-for-the-mobile-web~Friday 17 October 2014^
I've created a function which grabs the data and separates it out into an array using ^
as the delimter:
function getPostList(){
$masterposts = "../posts/master-allposts.txt";
$current = file_get_contents($masterposts);
$masterpostlist = explode('^', $current);
return $masterpostlist;
}
And the result is something like this:
array(3) { [0]=> string(46) "Example post one~example-post-one~Friday 17 October 2014" [1]=> string(83) " Wayfinding For The Mobile Web~wayfinding-for-the-mobile-web~Friday 17 October 2014" [2]=> string(0) "" }
However I'm now trying to break down that array further so I can output all the separate parts for each. Ideally as string vars $title, $filename and $publishdate
I got this far but I think I am running into problems as I'm possibly overwriting the array each time. How would you do this?
foreach ($masterpostlist as $post){
$postParts = explode('~',$post);
var_dump($postParts);
}
You can "convert" the array you already have by just replacing the original un-exploded variables with the exploded ones.
foreach ($masterpostlist as &$post){
$post = explode('~',$post);
}
This uses the reference &
operator and allows the code inside the foreach loop to change the variable of the loop. Other wise it would only change the temporary copy used inside the loop.
In your function, it would be used like this:
function getPostList(){
$masterposts = "../posts/master-allposts.txt";
$current = file_get_contents($masterposts);
$masterpostlist = explode('^', $current);
foreach ($masterpostlist as &$post){
$post = explode('~',$post);
}
return $masterpostlist;
}