$where = '1=1';$keyword = $_GET['keyword']; if($keyword) { $where['title'] = array('like', "%$keyword%");}var_dump($where);竟然列印出來:A=1到底是怎麼樣的轉換流程?
回複內容:
$where = '1=1';$keyword = $_GET['keyword']; if($keyword) { $where['title'] = array('like', "%$keyword%");}var_dump($where);竟然列印出來:A=1到底是怎麼樣的轉換流程?
首先,讓我來吐槽一下(不吐槽會死!):
$where是一個字串,你寫的$where['title']是個什麼鬼?
你把一個array賦值給一個字串中的一個字串,這又是什麼鬼?
我把你問題中的一些雜七雜八無用的代碼去除後,精簡一下問題:
$where = '1=1';$where['title'] = array();var_dump($where);
和上面的吐槽對應的是,我們也一步步來看:
$where['title']表達的是字串$where中下標為'title'的字元,注意下標的合法值是[0-字串長度減1],那麼php對於非法的下標,實際上是和$where[0]的作用是一致的。
這樣問題進一步簡化為:
$where = '1=1';$where[0] = array();var_dump($where);
瞭解了$where[0]實際上指的是$where字串的第一個字元,那麼下面就是要吐槽的“你把一個array賦值給一個字串中的一個字串,這又是什麼鬼?”
我們下面做一個測試:
var_dump( (string)array() );
你猜會輸出什嗎?
PHP Notice: Array to string conversion in /home/nfer/temp.php on line 8string(5) "Array"
那麼這裡就很好理解了,$where[0] = array();就是把字串Array賦值給$where字串的第一個字元。
bingo, the output is string(3) "A=1"
最後,讓我也寫一個鬧鬼的代碼:
$where = 'A=1';$keyword = $_GET['keyword']; if($keyword) { $where['title'] = $keyword == 123;}var_dump($where);
你覺得結果會輸出什麼呢?
1.$where = 1,這個沒錯把,首先這個是字串。
2.然後你又把$where當數組,並把$where['title'] = array('like',"xxx"),賦值過去,這不科學把。