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;
        }

    理想的结果是

  • 相关阅读:
    Javascript进阶篇——(函数)笔记整理
    Javascript进阶篇——(流程控制语句)笔记整理
    Javascript进阶篇——(数组)笔记整理
    Javascript进阶篇——(JS基础语法)笔记整理
    Javascript基础学习笔记
    wamp安装
    JavaScript语法作业
    0721JS
    css复习内容
    盒子模型
  • 原文地址:https://www.cnblogs.com/8000cabbage/p/7704354.html
Copyright © 2011-2022 走看看