簡體   English   中英

檢查數組中是否存在對象

[英]check existence of an object in array

起初我想說我是PHP的新手。

我有一個實現,檢查對象是否在數組中,如果沒有添加另一個數組。 但它總是返回false並在order數組中添加。

我該如何解決?

這里是部分代碼:

$temp = new tempClass($x, $y);

    if (!in_array($temp, $temp_array)) {
            $temp2_array[] = $temp;
    }

由於要在數組中添加實例,請確保數組in_array()使用嚴格模式比較:

$temp = new tempClass($x, $y);

if (!in_array($temp, $temp_array, true)) {
  $temp2_array[] = $temp;
}

此外,您需要了解類的2個不同實例,即使它們包含相同的數據,仍然是2個不同的實例。 如果要知道2個實例是否相同,您需要創建自己的循環並手動比較實例。

您可以省略嚴格模式,它將比較類的成員,但只要您有不同的成員,它就不相等。

$temp = new tempClass($x, $y);

if (!in_array($temp, $temp_array)) {
  $temp2_array[] = $temp;
}

我認為這是因為您正在檢查數組中新對象的引用,而不是該對象的值。 嘗試做:

print_r($temp_array);

看看你得到了什么......這應該讓你知道如何解決它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM