2012-07-16 43 views
0

我試圖在對象中創建元素的克隆併爲克隆設置新名稱。如何用另一個數組填充數組?

class My_Obj{ 
var $obj; 
var $obj_name; 
var clone;  //----int input to say how many clones are needed 
var clone_names;//----array input to make clone's name different from $obj 
function __construct($args = '') { 
    $defaults=array(
    /* codes to set up the default $obj */ 
) 
if ($this->clone >0){ 
    for ($i = 0; $i <= $this->clone; ++$i){ 
    $clone_obj[$i]['name'] = /* need to loop through array $clone_name to fill this */ 

} 
} 

/* other codes */ 
} 

例如,$ clone_names可以是數組('cat','dog','bird')。只要每個克隆獲得一個名稱,哪個訂單並不重要。我想學習如何做到這一點。謝謝!

+0

這是相當困難的理解你的要求。請輸入example * input data *和expected * output data *。 – deceze 2012-07-16 13:32:20

+0

強烈建議您採用[PHP5風格的類屬性定義](http://us3.php.net/manual/en/language.oop5.php)。 PHP4樣式'var'關鍵字不再使用。相反,你應該聲明這些爲「public」或「private」屬性。 – 2012-07-16 13:32:42

+0

我也弄不清楚。而且你也缺少一些$符號。 – Pete 2012-07-16 13:33:25

回答

0

如果我正確理解你的問題,你想填充數組$clone_obj的值從$clone_names - 直到在$clone指定的克隆數?

如果是這樣的情況下,這可能工作(我已經重寫你使用的示例類):

class My_Obj { 
    public $clone = 0;   //----int input to say how many clones are needed 
    public $clone_names = array(); //----array input to make clone's name different from $obj 
    private $clone_obj = array(); // array to store cloned names in 

    function __construct($args = '') { 
     for ($i=0; $i<$this->clone; $i++) { 
      // copy the name in "$clone_names" to "$clone_obj", if it exists 
     $this->clone_obj[$i] = array(); 
      $this->clone_obj[$i]['name'] = (isset($this->clone_names[$i]) ? $this->clone_names[$i] : ''); 
     } 
    } 
} 
+0

謝謝,這正是我需要的。 – Jenny 2012-07-16 13:55:07

+0

太棒了,很高興我能幫到你! – newfurniturey 2012-07-16 14:03:26