2012-03-26 36 views
1

我試圖在數組中使用動態對象內的值的值。

在我的具體情況我有一個這樣的數組。

$this->customer = array(
    [dealerId] => 4 
    [billFirstName] => Joe 
    [billLastName] => Blo 
    [billAddress1] => 1010s  
    [billAddress2] => 1020s 
    [billCity] => Anytown 
    [billState] => ST 
    [billCountry] => USA 
    [billPostalCode] => 11111 
    [dEmail] => emailaddress 
    [billPhone] => 8008008888 
    [password] => password 
    [distPrice] => 5 
    [distCost] => 20); 

$result = $this->keyCheck('dealerId', 'customer'); 

我使用的方法:

protected function keyCheck($key, $array, $type = false) 
    { 
     if(array_key_exists($key, $this->$array) && $this->$array[$key]): 
     return $this->$array[$key]; 
     else: 
     return $type; 
     endif; 
    } 

首先檢查工作(array_key_exists($鍵,$此 - > $陣列))。但是第二個檢查失敗($ this - > $ array [$ key]),即使在該數組的索引中存在一個值。我已經通過使用print_r($ this - > $ array)證明了該數組存在於keyCheck()方法內部。在方法裏面。我知道我正在尋找的價值可以通過使用,print $ this - > $ array ['dealerId'];

不要被掛了名,或方法我用,就是我中找出如何解決一個數組,它是動態的以這種方式處理保存的值很感興趣。

這可能那麼容易,一旦它發現我會拍着我的頭......

+1

你最好的var_dump if語句,你是可疑內的部分,看看你會得到什麼。 print_r不會信任空值。 – Melsi 2012-03-26 22:18:46

+0

如何使用isset()?它會改變什麼嗎? – 2012-03-26 22:22:18

+0

謝謝,我試過了,數組中沒有空值。的方法中的試驗「打印$此 - > $陣列[‘dealerId’]」產生我在尋找的價值,但解決由於某種原因不能正常工作的變量指標。 – Foaminator 2012-03-26 22:22:41

回答

4

您正在運行到可怕的治療字符串數組陷阱,即:

$str = 'customer'; echo $str[0]; // prints c 

$this->$array[$key]$array[$key]部分被解釋爲顯示字符串$ array的第n個索引(如果您通過customer它將嘗試訪問$this->c,這不存在)。首先將數組分配給一個變量。這裏有一個例子:

class A 
{ 
    public $customer = array('dealerId'=>4, 'billFirstName'=>'Joe'); 

    public function keyCheck($key, $arrayName, $type = false) 
    { 
     $array = $this->$arrayName; 
     if(array_key_exists($key, $array) && $array[$key]) { 
      return $array[$key]; 
     } else { 
      return $type; 
     } 
    } 
} 

$a = new A(); 
echo $a->keyCheck('billFirstName', 'customer'); // Joe 

或者,你可以使用複雜的語法:$this->{$arrayName}[$key]在Artjom的答案建議。

PHP 5.4 addresses this gotcha

[In PHP 5.4] Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them.

E_WARNING應該幫助開發人員更快速地追查原因。

+0

Gah !!!!!而已!謝謝! – Foaminator 2012-03-26 22:28:20

+0

不客氣。請儘快並勾選您的時間!我也會添加更多信息。 – webbiedave 2012-03-26 22:29:27

+0

我會給你一個「有用的答案」,但我還沒有足夠的代表。 :)當我嘗試 – Foaminator 2012-03-26 22:29:37

1

那麼u必須使用

$this->{$array}[$key]; 
+0

有趣的錯誤......「捕致命錯誤:類客戶的對象無法在/home/classes/Basic.class.php上線159轉換成字符串」 – Foaminator 2012-03-26 22:38:17

+0

事實上,因爲它工作得很好php 5.3.9 – 2012-03-26 22:44:48

+0

奇怪。這個語法應該早於5.2(甚至更早)。 – webbiedave 2012-03-26 23:01:50

相關問題