dqn48247
dqn48247
2015-09-23 16:39

如何从数组元素中获取后续元素?

已采纳

I am trying to get a specific line in a file and then next 2 lines after it. How can I get next 2 lines? The following is my code and file.

$context = 'context=regencyoutgoing';
$lines = file('/etc/asterisk/sip1.conf');
foreach($lines as $line)
{
    $find_context = strpos($line, $context);
    if($find_context !== false){
        echo $line;
    }
}   

Here is my sip1.conf:

[000201891]
type=friend
context=regencyoutgoing
username=000201891
callerid = <000201891>
host=dynamic
secret=198



[000202222]
type=friend
context=regencyoutgoing
username=000202222
callerid = <000202222>
host=dynamic
secret=2000
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongyin8009 dongyin8009 6年前

    This should work for you:

    First of all we get all array elements, which contain $context somewhere with preg_grep(). In your example something like this:

    Array
    (
        2  => context=regencyoutgoing
        12 => context=regencyoutgoing
    )
    

    After this we get the keys of the array with array_keys(). Then we simply loop through all keys and take a slice of 3 elements for each key with array_slice(), which we then merge to the result array with array_merge().

    Code:

     <?php
    
        $lines = file("/etc/asterisk/sip1.conf");
        $context = "context=regencyoutgoing";
        $matchedKeys = array_keys(preg_grep("/" . preg_qute($context, "/")  ."/", $lines));
        $result = [];
    
        foreach($matchedKeys as $key)
            $result = array_merge($result, array_slice($lines, $key, 3));
    
        print_r($result);
    
    ?>
    
    点赞 评论 复制链接分享
  • dreamMyDream2014 dreamMyDream2014 6年前

    Try this

    $result=[];
    foreach($lines as $i => $line)
    {
        $find_context = strpos($line, $context);
        if($find_context !== false){
            $result=[$lines[$i],$lines[$i+1],$lines[$i+2]];
    
        }
    }
    

    Example: https://eval.in/438416

    点赞 评论 复制链接分享
  • dpp34603 dpp34603 6年前

    This file is actually in .ini format, so you can try using parse_ini_file to read this.

    $data = parse_ini_file('/etc/asterisk/sip1.conf', TRUE);
    

    This gives you an associative array that you can then loop/search through as you need.

    Example: https://eval.in/438391

    点赞 评论 复制链接分享

相关推荐