douyuliu9527 2011-03-28 15:24
浏览 14

foreach循环问题

I made this code :

$matches = array();
preg_match_all('/"Type":".+?",/', $text, $matches);


foreach($matches[0] as $match) {
    if (isset($_GET['dvd']) && !empty($_GET['dvd'])) {
        $dvd = $_GET['dvd'];
        if (stripos($match, 'DVD') !== false) {
            $match = '';
        }
    }
    echo $match;
}

In this code i search for the word "type" in $text and it stores the whole line with the words ahead of it in the array. And then i loop through each one and see if the word DVD is there. If it is then, it removes it and displays a blank line.


Now I also want to search for suppose manufacturer and display it beneath every type returned.

So it should return suppose the result :

Type: HDD
Manufacturer: WD

Type: Flash Drive
Manufacturer: Transcend

Type: CD
Manufacturer: Sony

So I tried it with putting another preg_match_all expression:

$anotherMatch = array();
preg_match_all('/"Manufacturer":".+?",/', $text, $anotherMatch);

And I tried combining this with the previous foreach expression with an && operator but it didn't work. Also I tried different foreach expressions and then one for echoing at the end. but that also didn't work.

Can you tell me how to achieve the desired result. Thanks...

  • 写回答

1条回答 默认 最新

  • doushan1157 2011-03-28 20:26
    关注

    Given source input like this:

    "Type":"HDD",
    "Manufacturer":"WD",
    "Other":"Nonsense",
    "Type":"Flash Drive",
    "Manufacturer":"Transcend",
    "Other":"More nonsense",
    "Type":"CD",
    "Manufacturer":"Sony",
    "Other":"Yet even more nonsense",
    

    And expecting output like this:

    Type: HDD
    Manufacturer: WD
    
    Type: Flash Drive
    Manufacturer: Transcend
    
    Type: CD
    Manufacturer: Sony
    

    You could use this regular expression:

    /"(Type|Manufacturer)":"([^"]+?)",/
    

    And loop over it like this:

    preg_match_all('/"(Type|Manufacturer)":"([^"]+?)",/', $text, $matches);
    
    foreach($matches[0] as $match => $line)
    {
        if (!empty($_GET['dvd']) && stripos($matches[2], 'DVD') !== false)
        {
            continue;
        }
        echo $matches[1][$match] . ': ' . $matches[2][$match] . "
    ";
    }
    

    Although, I don't think that will do quite exactly what you want it to.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分