dourang20110122 2014-10-17 14:51
浏览 40

按特定字符拆分文档,然后进一步拆分为变量

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);
}
  • 写回答

1条回答 默认 最新

  • dongyou4411 2014-10-17 14:55
    关注

    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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据