problem with PHP References
I have the following PHP function
protected function &__group($ar_path, $b_create) {
assert('is_null($ar_path) || is_array($ar_path)');
$parent = &$this->ma_config;
if (!is_null($ar_path) && (count($ar_path) > 0)) {
if ($b_create) {
// Get with Create is necessary
foreach ($ar_path as $group) {
if (!array_key_exists('groups', $parent)) {
/*MARKER*/ $parent['groups'] = array($group => array());
// Mark the File as Modified
$this->mb_dirty = true;
continue;
}
$parent = &$parent['groups'];
if (!array_key_exists($group, $parent)) {
$parent[$group] = array();
// Mark the File as Modified
$this->mb_dirty = true;
continue;
}
$parent = &$parent[$group];
}
} else {
// Simple Get
foreach ($ar_path as $group) {
$parent = array_extract_key(
array('groups', $group),
$parent,
'is_array'
开发者_Go百科 );
if (is_null($parent)) {
break;
}
}
}
}
return $parent;
}
The function is supposed to allow me to create 'groups' at any level (i.e. nested groups).
What seems to be the problem is the way PHP handles references.
When I send in something like ar_path('level 1','level 2')
, the function should create a child group to 'level 1' if it doesn't exist.
Therefore given something like:
$this->ma_config = array(
'groups' => array(
'level 1' => array(
'values' => array(
'1',
'2'
)
)
)
);
I should end up with something like:
$this->ma_config = array(
'groups' => array(
'level 1' => array(
'groups' => array(
'level 2' => array()
),
'values' => array(
'1',
'2'
)
)
)
);
The problem is that, on my second pass through the loop, when I run line /*MARKER*/
to create the second level (i.e. which should have resulted in $this->ma_config['groups']['level 1]['groups']['level 2'] = array()
) it destroys the 'level 1' instead (it seems, from the debugger, that PHP ends up doing this instead $this->ma_config['groups']['level 1] = array()
)
Why?
I'm not really sure what your function is doing because of how complicated it is. Consider using this simple code to augment your data structure. Then, separate any operations or look ups into a different function.
<?php
$ma_config = array(
'groups' => array(
'level 1' => array(
'values' => array(
'1',
'2'
)
)
)
);
$ar_path = 'level 1';
$b_create = 'level 2';
$newGroup =& $ma_config['groups'][$ar_path]['groups'][$b_create];
$newGroup = (array) $newGroup;
unset($newGroup);
print_r($ma_config);
精彩评论