2015-02-05 22 views
0

我發現兩個陣列$item$query之間的交點分別爲:注意:Array對字符串的轉換PHP

Array ([0] => twitter [1] => 1 [2] => 561522539340771328 [3] => Array ())

Array ([0] => dig [1] => twitter)

這是代碼我有:

if (array_intersect ($query, $item)) { 
      $intersection [] = $item; 
} 

它以某種方式返回此問題標題中定義的通知。要麼我太累,不能注意到有什麼問題,否則我可能會發瘋,不應該返回Array ([0] => twitter)

+4

這是因爲你的第一個數組末尾有空的數組,所以刪除它並且它應該可以正常工作,這樣做對你來說還是不能改變數組? (順便說一句:現在你只要將'$ item'數組賦值給'$ intersection',但我想你想將'array_intersect'的輸出賦值給一個變量,然後你就可以使用它了) – Rizier123 2015-02-05 22:02:30

+0

從技術上講,我無法刪除因爲該數組可能包含提取位置的列表,但是如果沒有找到位置,我會將其修改爲0。謝謝! 其實'$交集'中的'$ item'賦值是爲了! – jablesauce 2015-02-05 22:25:32

+0

寫了一個答案,如果你有一個多維數組,你可以使用['array_uintersect()'](http://php.net/manual/en/function.array-uintersect.php)來比較這些值。 – Rizier123 2015-02-05 22:32:44

回答

2

這是因爲您在第一個數組的末尾有一個空數組,array_intersect()將嘗試將其轉換爲一個字符串,從而導致出現此錯誤。

但要擺脫這種錯誤的,你可以使用array_filter()這樣的:

(另外你要分配array_intersect的輸出,然後用這個)

<?php  

    $item = array("twitter", 1, 561522539340771328, array()); 
    $query = array("dig", "twitter"); 

    if ($intersect = array_intersect($query, array_filter($item))) { 
              //^^^^^^^^^^^^ See here 
     $intersection [] = $intersect; 
    } 

    print_r($intersection); 

?> 

輸出:

Array ([0] => Array ([1] => twitter)) 
+0

我試過這個,但它仍然不會工作,因爲它可能有時包含位置數組不會總是空的。我不知道這是由於最後一個元素是一個數組,雖然非常感謝。我找到了一個解決方案,很快發佈! – jablesauce 2015-02-05 22:39:35

相關問題