Good Evening - I'm trying to create a multi-dimensional array based on a blown text string of account codes stored in a database. Account codes will have different lengths / depths. Say, for example, $ test in the array below is similar to the results that I would pull from a database:
$test = array(
'110|5100|120' => 'Teacher Salaries',
'110|5100|130' => 'Other Professoinal Services',
'110|5100|510|1' => 'Primary Supplies',
'110|5100|510|2' => 'Intermediate Supplies',
'110|7300|110' => 'Administrator Salaries',
'110|7300|510' => 'Administrative Supplies',
'763|5100' => 'Academic Grants'
);
foreach($test AS $k => $v) {
$lvl = explode("|", $k);
}
I want to create a function that will return an array, such as:
[110] => Array
(
[5100] => Array
(
[120] => Teacher Salaries
[130] => Other Professional Services
[510] => Array
(
[1] => Primary Supplies
[2] => Intermediate Supplies
)
)
[7300] => Array
(
[110] => Administrator Salaries
[510] => Supplies
)
)
[763] => Array
(
[5100] => Academic Grants
)
I was able to come up with a function that can take one of the codes and correctly break it into an array, but when I try to combine them together, they lose their keys. Here is what I still have:
function expandedArray($codes, $value) {
$decoded = explode("|",$codes);
RETURN expandedArraySub($decoded, $value);
}
function expandedArraySub($decoded = array(), $value = Null) {
$k = array_pop($decoded);
$out[$k] = $value;
if(is_array($decoded) && count($decoded) > 0) { $out = expandedArraySub($decoded, $out); }
RETURN $out;
}
But when I run the following, instead of getting what I want, as described above, I get an array that loses the key "110":
$r1 = expandedArray('110|5100|510|1', "Primary Supplies");
// $r1 is now [ 110 => [5100 => [510 => [ 1 ] ] ] ]
$r2 = expandedArray('110|5100|510|2', 'Intermediate Supplies');
// $r2 is now [ 110 => [5100 => [510 => [ 2 ] ] ] ]
$r = array_merge($r1, $r2);
, , , . :
[0] => Array
(
[5100] => Array
(
[510] => Array
(
[1] => Primary Supplies
)
)
)
[1] => Array
(
[5100] => Array
(
[510] => Array
(
[2] => Intermediate Supplies
)
)
)
! !