~Onlooker
2009-10-07 16:11
采纳率: 0%
浏览 698
已采纳

是否有一个函数将 PHP 数组复制到另一个数组?

Is there a function to make a copy of a PHP array to another?

I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.

转载于:https://stackoverflow.com/questions/1532618/is-there-a-function-to-make-a-copy-of-a-php-array-to-another

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

16条回答 默认 最新

  • 斗士狗 2009-10-07 17:56
    已采纳

    In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:

    $a = array();
    $b = $a;
    $b['foo'] = 42;
    var_dump($a);
    

    Will yield:

    array(0) {
    }
    

    Whereas:

    $a = new StdClass();
    $b = $a;
    $b->foo = 42;
    var_dump($a);
    

    Yields:

    object(stdClass)#1 (1) {
      ["foo"]=>
      int(42)
    }
    

    You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.

    Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 7*4 2009-10-07 16:13

    When you do

    $array_x = $array_y;
    

    PHP copies the array, so I'm not sure how you would have gotten burned. For your case,

    global $foo;
    $foo = $obj->bar;
    

    should work fine.

    In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.

    评论
    解决 无用
    打赏 举报
  • derek5. 2009-10-07 16:13

    PHP will copy the array by default. References in PHP have to be explicit.

    $a = array(1,2);
    $b = $a; // $b will be a different array
    $c = &$a; // $c will be a reference to $a
    
    评论
    解决 无用
    打赏 举报
  • larry*wei 2012-12-08 07:56

    array_merge() is a function in which you can copy one array to another in PHP.

    评论
    解决 无用
    打赏 举报
  • 北城已荒凉 2013-07-18 16:35

    If you have an array that contains objects, you need to make a copy of that array without touching its internal pointer, and you need all the objects to be cloned (so that you're not modifying the originals when you make changes to the copied array), use this.

    The trick to not touching the array's internal pointer is to make sure you're working with a copy of the array, and not the original array (or a reference to it), so using a function parameter will get the job done (thus, this is a function that takes in an array).

    Note that you will still need to implement __clone() on your objects if you'd like their properties to also be cloned.

    This function works just as well for any type of array (including mixed type).

    function array_clone($array) {
        return array_map(function($element) {
            return ((is_array($element))
                ? call_user_func(__FUNCTION__, $element)
                : ((is_object($element))
                    ? clone $element
                    : $element
                )
            );
        }, $array);
    }
    
    评论
    解决 无用
    打赏 举报
  • 胖鸭 2014-08-20 19:26

    Since this wasn't covered in any of the answers and is now available in PHP 5.3 (assumed Original Post was using 5.2).

    In order to maintain an array structure and change its values I prefer to use array_replace or array_replace_recursive depending on my use case.

    http://php.net/manual/en/function.array-replace.php

    Here is an example using array_replace and array_replace_recursive demonstrating it being able to maintain the indexed order and capable of removing a reference.

    http://ideone.com/SzlBUZ

    The code below is written using the short array syntax available since PHP 5.4 which replaces array() with []. http://php.net/manual/en/language.types.array.php

    Works on either offset indexed and name indexed arrays

    $o1 = new stdClass;
    $a = 'd';
    //This is the base array or the initial structure
    $o1->ar1 = ['a', 'b', ['ca', 'cb']];
    $o1->ar1[3] = & $a; //set 3rd offset to reference $a
    
    //direct copy (not passed by reference)
    $o1->ar2 = $o1->ar1; //alternatively array_replace($o1->ar1, []);
    $o1->ar1[0] = 'z'; //set offset 0 of ar1 = z do not change ar2
    $o1->ar1[3] = 'e'; //$a = e (changes value of 3rd offset to e in ar1 and ar2)
    
    //copy and remove reference to 3rd offset of ar1 and change 2nd offset to a new array
    $o1->ar3 = array_replace($o1->ar1, [2 => ['aa'], 3 => 'd']);
    
    //maintain original array of the 2nd offset in ar1 and change the value at offset 0
    //also remove reference of the 2nd offset
    //note: offset 3 and 2 are transposed
    $o1->ar4 = array_replace_recursive($o1->ar1, [3 => 'f', 2 => ['bb']]);
    
    var_dump($o1);
    

    Output:

    ["ar1"]=>
      array(4) {
        [0]=>
        string(1) "z"
        [1]=>
        string(1) "b"
        [2]=>
        array(2) {
          [0]=>
          string(2) "ca"
          [1]=>
          string(2) "cb"
        }
        [3]=>
        &string(1) "e"
      }
      ["ar2"]=>
      array(4) {
        [0]=>
        string(1) "a"
        [1]=>
        string(1) "b"
        [2]=>
        array(2) {
          [0]=>
          string(2) "ca"
          [1]=>
          string(2) "cb"
        }
        [3]=>
        &string(1) "e"
      }
      ["ar3"]=>
      array(4) {
        [0]=>
        string(1) "z"
        [1]=>
        string(1) "b"
        [2]=>
        array(1) {
          [0]=>
          string(2) "aa"
        }
        [3]=>
        string(1) "d"
      }
      ["ar4"]=>
      array(4) {
        [0]=>
        string(1) "z"
        [1]=>
        string(1) "b"
        [2]=>
        array(2) {
          [0]=>
          string(2) "bb"
          [1]=>
          string(2) "cb"
        }
        [3]=>
        string(1) "f"
      }
    
    评论
    解决 无用
    打赏 举报
  • bug^君 2015-03-11 02:32

    This is the way I am copying my arrays in Php:

    function equal_array($arr){
      $ArrayObject = new ArrayObject($arr);
      return $ArrayObject->getArrayCopy();  
    }
    
    $test = array("aa","bb",3);
    $test2 = equal_array($test);
    print_r($test2);
    

    This outputs:

    Array
    (
    [0] => aa
    [1] => bb
    [2] => 3
    )
    
    评论
    解决 无用
    打赏 举报
  • 笑故挽风 2015-05-29 10:57
    <?php
    function arrayCopy( array $array ) {
            $result = array();
            foreach( $array as $key => $val ) {
                if( is_array( $val ) ) {
                    $result[$key] = arrayCopy( $val );
                } elseif ( is_object( $val ) ) {
                    $result[$key] = clone $val;
                } else {
                    $result[$key] = $val;
                }
            }
            return $result;
    }
    ?>
    
    评论
    解决 无用
    打赏 举报
  • 零零乙 2016-03-13 07:54

    If you have only basic types in your array you can do this:

    $copy = json_decode( json_encode($array), true);
    

    You won't need to update the references manually
    I know it won't work for everyone, but it worked for me

    评论
    解决 无用
    打赏 举报
  • 北城已荒凉 2016-07-29 19:12

    Define this:

    $copy = create_function('$a', 'return $a;');
    

    Copy $_ARRAY to $_ARRAY2 :

    $_ARRAY2 = array_map($copy, $_ARRAY);
    
    评论
    解决 无用
    打赏 举报
  • 零零乙 2016-11-04 21:26

    simple and makes deep copy breaking all links

    $new=unserialize(serialize($old));
    
    评论
    解决 无用
    打赏 举报
  • 10.24 2017-01-05 13:52

    Safest and cheapest way I found is:

    <?php 
    $b = array_values($a);
    

    This has also the benefit to reindex the array.

    This will not work as expected on associative array (hash), but neither most of previous answer.

    评论
    解决 无用
    打赏 举报
  • 三生石@ 2017-04-06 05:39

    In php array, you need to just assign them to other variable to get copy of that array. But first you need to make sure about it's type, whether it is array or arrayObject or stdObject.

    For Simple php array :

    $a = array(
    'data' => 10
    );
    
    $b = $a;
    
    var_dump($b);
    
    output:
    
    array:1 [
      "data" => 10
    ]
    
    评论
    解决 无用
    打赏 举报
  • 程序go 2017-07-14 11:54
    private function cloneObject($mixed)
    {
        switch (true) {
            case is_object($mixed):
                return clone $mixed;
            case is_array($mixed):
                return array_map(array($this, __FUNCTION__), $mixed);
            default:
                return $mixed;
        }
    }
    
    评论
    解决 无用
    打赏 举报
  • 谁还没个明天 2018-03-16 12:20

    simple and neat for PHP >= 5.3

    $cloned = array_replace([], $YOUR_ARRAY);

    array_replace (or array_replace_recursive). For me the cleanest way and just like Object.assign from JavaScript.

    $original = [ 'foo' => 'bar', 'fiz' => 'baz' ];
    
    $cloned = array_replace([], $original);
    $clonedWithReassignment = array_replace([], $original, ['foo' => 'changed']);
    $clonedWithNewValues = array_replace([], $original, ['add' => 'new']);
    
    $original['new'] = 'val';
    

    will result in

    // original: 
    {"foo":"bar","fiz":"baz","new":"val"}
    // cloned:   
    {"foo":"bar","fiz":"baz"}
    // cloned with reassignment:
    {"foo":"changed","fiz":"baz"}
    // cloned with new values:
    {"foo":"bar","fiz":"baz","add":"new"}
    
    评论
    解决 无用
    打赏 举报
  • YaoRaoLov 2018-09-29 15:36

    $arr_one_copy = array_combine(array_keys($arr_one), $arr_one);

    Just to post one more solution ;)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题