2011-05-12 58 views
0

我在zend項目中測試模型,我有一個關於如何獲得數組值的問題,我發現它不能使用$array[index];如何獲取數組的值?

這是find方法我測試:

static function find($name, $order=null, $limit=null, $offset=null) { 
     return self::_selectAndBind(
       get_class(), 
         self::getDefaultAdapter() 
         ->select() 
         ->from('user') 
         ->where('name = ?', array($name)) 
         ->order($order) 
         ->limit($limit, $offset) 
     ); 
    } 

這是測試用例find()方法:

public function testUser2CanFind() { 
     $this->assertNotNull($this->_model->find('yes')); 

     $this->assertEquals(1, count($this->_model->find('yes'))); 

     print_r($this->_model->find('yes')); 
     //$this->assertEquals('admin',$this->_model->find('yes')[0]->login); 
    } 

我想登錄名的值,所以我們我print_r($this->_model->find('yes'));它給:

......Array 
(
    [0] => Application_Model_User2 Object 
     (
      [_table:protected] => user 
      [_primary:protected] => Array 
       (
        [0] => id 
       ) 

      [_primary_ai:protected] => id 
      [_data:protected] => Array 
       (
        [id] => 1 
        [created] => 2011-05-03 09:41:2 
        [login] => admin 
        [password_hash] => c8ebe700df11 
        [name] => yes 
        [surname] => 
        [gender] => 
        [street] => 
        [postal_code] => 
        [city] => 
        [mobile] => 
        [homephone] => 
        [email] => 
        [is_active] => 1 
       ) 

      [_data_changed:protected] => Array 
       (
       ) 

      [_readonly:protected] => Array 
       (
        [0] => id 
       ) 

      [_db:protected] => 
     ) 

) 

我怎麼能得到[login] => admin價值?我試圖使用$this->_model->find('yes')[0],但它給出了錯誤,任何人都可以幫忙嗎?

+0

Deferenced陣列尚未公佈,你不能直接使用$這 - > _model->找到( '是')[0]。你必須使用一個臨時變量。 – grunk 2011-05-12 08:39:51

+0

'$ this - > _ model-> find('yes') - > current()''怎麼辦?我假設你的find方法返回一個行集。 – Marcin 2011-05-12 08:43:00

+0

@Marcin:只要你能避免它,你不應該直接調用「魔術方法」。 ':: current()'被函數'current()'調用。改爲使用它。 – KingCrunch 2011-05-12 09:54:20

回答

1
$entity = current($this->_model->find('yes')); 
echo $entity->login; 

更新:

如果在此列表中超過一個元素是,使用普通的迭代

foreach($this->_model->find('yes') as $entity) 
    echo $entity->login; 
+0

現在這個數組中只有一個元素,但是如果這個數組中有幾個元素呢? – 2011-05-12 09:20:13