2011-12-19 56 views
-1

與mysql_fetch_object()工作時那麼喜歡,你怎麼做這樣的事情:如何動態添加到對象數組?

$array = array(); 
while($row = mysql_fetch_object($result)) 
{ 
    $array[] = $row; 
} 

你如何實現與對象而不是數組?像,

$object = new stdClass; 
while($row = mysql_fetch_object($result)) 
{ 
    $object[] = $row; 
} 

有沒有辦法做到這一點,沒有很多醜陋的類型轉換?

+0

這並不真正使一個很大的意義。你想讓結果對象看起來像什麼? – deceze 2011-12-19 07:36:15

+0

你能否澄清預期結果需要做些什麼?你想要迭代對象嗎? – SeanNieuwoudt 2011-12-19 07:41:59

+1

你想訪問這樣的行嗎? $ object-> 0-> COLUMN 這是不可能的。實際上它沒有任何意義。 – 2011-12-19 07:57:14

回答

2

第一種方法是正確的,
應該所有對象分配到$array
像一個數組,
您可以通過

$arr[0]->$COLUMN ... 

我敢打賭,你是不是指這個訪問: -

$object = new stdClass; 
while($row = mysql_fetch_object($result)) 
{ 
    $props = "object_{$cnt}"; 
    $object->$props = $row; 
    ++$cnt; 
} 

第二種方法是每個對象分配到$對象的屬性,
,您可以在屬性分配爲: -

$object->object_0->$COLUMN ... 
+0

我知道,但如果我想用對象訪問它,該怎麼辦?如果你只是把它變成一個數組,那麼使用mysql_fetch_object有什麼意義。編輯:哎呀,誤讀你的文章。 – CrazeD 2011-12-19 07:36:37

+0

如果你有興趣,你可以看看對象的SPL存儲http://php.net/manual/en/class.splobjectstorage.php – ajreal 2011-12-19 07:40:11

0

其他語言(如C++,C#和Java)的支持「仿製藥」,這樣你就不必做「很多醜陋的類型轉換的」。 PHP不會 - 因此一般需要演員。

但是在你的情況下......如果當你將數組放入數組中時,「$ row」作爲一個對象出現......當你去引用數組時,你不會得到同樣的對象嗎?

+0

PHP數組大約是一般的,它的泛型的想法doesn' t真的適用於PHP。 – deceze 2011-12-19 07:38:41

0
$object = array(); 
while($row = mysql_fetch_object($result)) 
{ 
    $object[] = $row; 
} 
$object = new stdClass($object); 

class myClass{ 
    private $counter = 0; 
    public function add($row){ 
     $count = $counter++; 
     $this->$count = $row; 
    } 
} 
$object = new myClass(); 
while($row = mysql_fetch_object($result)) 
{ 
    $object->add($row); 
} 

class myClass implements ArrayAccess{ 
    private $counter = 0; 
    public function offsetSet($offset, $value) { 
     if (is_null($offset)) { 
      $count = $counter++; 
      $this->$count = $value; 
     } else { 
      $this->$offset = $value; 
     } 
    } 
    public function offsetExists($offset) { 
     return isset($this->$offset); 
    } 
    public function offsetUnset($offset) { 
     unset($this->$offset); 
    } 
    public function offsetGet($offset) { 
     return isset($this->$offset) ? $this->$offset : null; 
    } 
} 
$object = new myClass(); 
while($row = mysql_fetch_object($result)) 
{ 
    $object[] = $row; 
}