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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题