Reputation: 2247
The Array:
$array = [
'A',
'B',
'C'
//and so on
]
Expected result:
$array = [
[
'value' => 'A',
'names' => [
'1' => 'A',
'2' => 'A'
],
'child' => [
'value' => 'B',
'names' => [
'1' => 'B',
'2' => 'B'
],
'child' => [
'value' => 'C',
'names' => [
'1' => 'C',
'2' => 'C'
],
'child' => [
// and so on...
]
]
]
]
];
I've researched a function array_merge_recursive
.
But this function doesn't shift array.
Need to achieve: staggered array from simple array.
Upvotes: 0
Views: 20
Reputation: 12939
I've not understood what you want inside names
, however this code is generating the array you want:
$array = [
'A',
'B',
'C'
//and so on
];
$result = [];
for($i = count($array) - 1 ; $i >= 0 ; $i--){
$result = [
'value' => $array[$i],
'names' => [
'1' => $array[$i],
'2' => $array[$i],
],
'child' => $result
];
}
Output:
Array
(
[value] => A
[names] => Array
(
[1] => A
[2] => A
)
[child] => Array
(
[value] => B
[names] => Array
(
[1] => B
[2] => B
)
[child] => Array
(
[value] => C
[names] => Array
(
[1] => C
[2] => C
)
[child] => Array
(
)
)
)
)
Upvotes: 1