Deep copy of PHP array of references

前端 未结 2 1353
温柔的废话
温柔的废话 2020-12-06 16:32

So $array is an array of which all elements are references.

I want to append this array to another array called $results (in a loop), but since they are references,

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 17:07

    no need to compare array_map with serialize cause array_map is not useful.

    $original = array('key'=>'foo');
    $array_of_reference = array(&$original);
    function myclone($value)
    {
      return $value;
    }
    $array_by_myclone = array();
    $array_by_myclone[] = array_map('myclone', $array_of_reference);
    
    $array_by_assignment = array();
    $array_by_assignment[] = $array_of_reference;
    
    $original['key'] = 'bar';
    
    var_dump($array_by_myclone[0][0]['key']); // bar, still a reference                                                                                                                                   
    var_dump($array_by_assignment[0][0]['key']); // bar, still a reference   
    

    array_map Applies the callback to the elements of the given arrays, just like foreach. if the array you want to copy has more than 1 nest, array_map does not work.

提交回复
热议问题