PHP, arrays and links

Why is the following code not working as I expected?

<?php $data = array( array('Area1', null, null), array(null, 'Section1', null), array(null, null, 'Location1'), array('Area2', null, null), array(null, 'Section2', null), array(null, null, 'Location2') ); $root = array(); foreach ($data as $row) { if ($row[0]) { $area = array(); $root[$row[0]] =& $area; } elseif ($row[1]) { $section = array(); $area[$row[1]] =& $section; } elseif ($row[2]) { $section[] = $row[2]; } } print_r($root); 

Expected Result:

 Array( [Area1] => Array( [Section1] => Array( [0] => Location1 ) ) [Area2] => Array( [Section2] => Array( [0] => Location2 ) ) ) 

Actual result:

 Array( [Area1] => Array( [Section2] => Array( [0] => Location2 ) ) [Area2] => Array( [Section2] => Array( [0] => Location2 ) ) ) 
+4
source share
2 answers

If you change the code to two lines as follows:

 $area = array(); $section = array(); 

:

 unset($area); $area = array(); unset($section); $section = array(); 

It will work as expected.

In the first version, $area and $section act as "pointers" to the value inside the $root array. If you first specify reset values, these variables can then be used to create new arrays instead of overwriting previous arrays.

+3
source

This will also work:

 $root[$row[0]] = array(); $area =& $root[$row[0]]; 
+1
source

Source: https://habr.com/ru/post/1276538/


All Articles