Im trying to split navigation position strings into a master array.
For example, If I have an item that's position is 1.2.2
I would like to add it in the master array as follows
1 =>
2 =>
2 => array()
And then if another item has '2.1'
1 =>
2 =>
2 => array()
2 =>
1 => array()
and then another '1.2.3'
1 =>
2 =>
2 => array()
3 => array()
2 =>
1 => array()
does anyone know of a way for doing this?
regards
edit
lets say I have a one dimensional array of objectects, I want to loop through them and store as a structured "navigation" like nested array. Each item has a navigation position string, i.e. 1.2.3.6
I then was thinking of $depth = explode( '.', $details['navigation_pos'] );
running it through some kind of array walker to place the object in the correct position.
hope this helps
edit
maybe a better way to put it is this, but more elegantly:
$depth = explode( '.', '1.2.3.4' );
$bar = json_decode( '{"' . implode( '":{"', $depth ) . '":[]' . str_repeat( '}', sizeof( $depth ) ) );
print_r($bar);
which would give
stdClass Object
(
[1] => stdClass Object
(
[2] => stdClass Object
(
[3] => stdClass Object
(
[4] => Array
(
)
)
)
)
)
You could use the eval()
construct, but beware:
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
$final_array = array(); // The output array
/*
Example:
$big_array = array(
'1.1' => 'One-one',
'2.1.3.4' => 'Two-one-three-four'
);
*/
foreach ($big_array as $position_string => $item)
{
$index_array = explode(".", $position_string);
foreach ($index_array as $key => $value)
{
// Make sure only integers are put through eval()
$index_array[$key] = (int)$value;
}
$indexes = implode("][", $index_array);
// TODO: make sure $item is safe to put through eval()!
eval("\$final_array[{$indexes}] = \$item");
}