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 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用