如何用另一个数组填充数组?

时间:2012-07-16 13:28:32

标签: php arrays

我正在尝试在对象中创建元素的克隆并为克隆设置新名称。

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')。只要每个克隆获得一个名称,哪个顺序无关紧要。我想学习如何做到这一点。谢谢!

1 个答案:

答案 0 :(得分: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] : '');
        }
    }
}