douyi5157 2014-07-27 16:12
浏览 52
已采纳

回声出第一个foreach数组

I am using this piece of code with using Simple Html dom :

$google = "http://www.google.com/something.";

 $html = file_get_html($google_html);

 foreach ($html->find('span[class=st]') as $element) 

    echo $element->innertext;

But i just want to echo out the first one of $element->innertext.

How can i just echo out first one ?

The above code echo's all elements.

  • Is there any way to stop the searching of simpledom , when the first child of array get found ?

I mean we don't need to get ALL of the elements, we just need the first one, so it's wasting time to picking all elements and them picking up the first one !

the Better is that when the fist one , got found , the SimpleDom get stop for finding new items.

  • 写回答

2条回答 默认 最新

  • duandai2178 2014-07-27 16:14
    关注

    Use break() after the first iteration.

    foreach ($html->find('span[class=st]') as $element){
        echo $element->innertext;
        break;
    }
    

    You can read more about break() in this documentation from PHP.net: http://php.net/manual/en/control-structures.break.php


    But I'd use this method to get the first element of the array instead:

    echo $html->find('span[class=st]')->innertext;
    

    No need to loop.

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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号