PHP dereference array elements

前端 未结 3 778
遥遥无期
遥遥无期 2021-01-18 08:50

I have 2 arrays.

$result = array();
$row = array();

Row\'s elements are all references and is constantly changing. For each iteration of

相关标签:
3条回答
  • 2021-01-18 09:22

    Not sure I totally understand the question, but can you use recursion?

    function array_copy($source) {
        $arr = array();
    
        foreach ($source as $element) {
            if (is_array($element)) {
                $arr[] = array_copy($element);
            } else {
                $arr[] = $element;
            }
        }
    
        return $arr;
    }
    
    $result = array();
    $row = array(
        array('a', 'b', 'c'),
        array('d', 'e', 'f')
    );
    
    $result[] = array_copy($row);
    
    $row[0][1] = 'x';
    
    var_dump($result);
    var_dump($row);
    
    0 讨论(0)
  • 2021-01-18 09:32

    Extending the function above like follows solved a problem I had:

    function array_copy($source) {
        $arr = array();
    
        foreach ($source as $element) {
            if (is_array($element)) {
                $arr[] = array_copy($element);
            } elseif (is_object($element)) {
                // make an object copy
                $arr[] = clone $element;
            } else {
                $arr[] = $element;
            }
        }
        return $arr;
    }
    
    0 讨论(0)
  • 2021-01-18 09:38
    $result = array_map(function($_){return $_;}, $row);
    
    0 讨论(0)
提交回复
热议问题