zoukankan      html  css  js  c++  java
  • 关于php ‘==’ 与 '===' 遇见的坑

    两个的区别所有PHPer都知道,

    今天在遍历 xmlNode时,自己写的代码就碰坑了

    想遍历xmlNode为数组

    得到的xmlNode为

    想要把所有的simpleXmlElement对象都遍历转成数组,并且去掉comment(注释)

    开始写的代码是这样的

        private function _xmlObj2Arr($xmlNode)
        {
            $arr = [];
            foreach ((array)$xmlNode as $key => $value) {
                if ($key == 'comment') continue;
                if ($value instanceof SimpleXMLElement || is_array($value)) {
                    $arr[$key] = $this->_xmlObj2Arr($value);
                } else {
                    $arr[$key] = trim($value);
                }
            }
            return $arr;
        }

    但是结果返回的总是空数组,

    这就纳闷了,怎么continue直接跳出来了,经过排查执行到第一个判断'comment‘就跳出了整个foreach。

    最终找到原因

    comment应该用’===‘

    第一次循环的 时候 var_dump( 0 == 'commnet') //true 

    so

    正确的代码应该是这样的,其实就是把'=='换成了'==='

        private function _xmlObj2Arr($xmlNode)
        {
            $arr = [];
            foreach ((array)$xmlNode as $key => $value) {
    
                if ($key === 'comment') continue;
                if ($value instanceof SimpleXMLElement || is_array($value)) {
                    $arr[$key] = $this->_xmlObj2Arr($value);
                } else {
                    $arr[$key] = trim($value);
                }
            }
            return $arr;
        }

    理想的结果是

  • 相关阅读:
    CPU Cache与缓存行
    linux 查看命令总结
    idea自个常用工具的总结
    《人月神话》
    啊哈,翻转
    Scrapy爬虫之豆瓣TOP250
    87的100次幂除以7的余数是多少
    python之sqlite3 用法详解
    Sublime Text 3 插件SublimeLinter/PEP8安装&配置,检查代码规范
    urlparse之urljoin() 爬虫必备
  • 原文地址:https://www.cnblogs.com/8000cabbage/p/7704354.html
Copyright © 2011-2022 走看看