douzhuangna6906 2012-04-03 00:34
浏览 30
已采纳

Php和javascript数组 - 跳过空白值并添加到新数组?

I have an array in php that contains all the lines of a text files (each line being one value of the array). My text file had blank lines so the array has blank lines too. I wanted to search the array for a certain value like this:

$array = array();

        $lines = file("textfile.txt"); //file in to an array
        foreach ($lines as $line)
        {
            if (stripos($line, "$$") !== false) 
            {
                $array[] = str_replace("$$", "", $line);

            }
        }

The code above is searching for a $$ and replacing it with a blank. The text file holds a line with a $$1 or any number and I want it to find all instances of that line, which it is doing.

My problem is that I want it to find the next 5 lines that aren't blank after finding the $$(number) and put them into a multi dimensional array. The multidimensional array looking similar to this (the program is a test in case you are wondering why the array is named the way it is):

$test = array(
    array('question' => 'What is the answer', 'ansa' => "answera", 'ansb' => "answerb", 'ansc' => "answerc", 'ansd' => "answerd"), // $test[1]
    array('question' => 'What is the answer', 'ansa' => "answera", 'ansb' => "answerb", 'ansc' => "answerc", 'ansd' => "answerd"), // $test[2]
);

The next five lines after the $$(number) are a question and four answers that need to go into the array. My code with regxp and searching isn't working so i discarded it.

  • 写回答

2条回答 默认 最新

  • dosrmo0442 2012-04-03 00:46
    关注

    you can try something like this...

    <?php
    
    $lines = array_filter(file('text.txt')); //file in to an array
    $questions = array();
    
    // find your starts and pull out questions
    foreach ($lines as $k=>$line)
    {
        if (stripos($line, "$$") !== false) 
        {
            $questions[] =  array_slice($lines, $k, 5);
        }
    }
    
    
    // dump
    var_dump($questions);
    

    See php manual for array_slice

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)