I have array that contains 4 levels of nesting:
$data = [
"" => [
'sub_level_1' => [
'sub_level_2' => [
'sub_level_3' => [
0 => ""
1 => "val"
]
]
]
],
"top_level_2" => [
'sub_level_1' => [
'sub_level_2' => [
'sub_level_3' => [
0 => ""
1 => "some_val"
2 => "foo"
]
]
]
]
];
I want to add other unique identifier for each nested level, so I use a counter on each level:
$top_level_counter = 0;
$sub_level_1_counter = 0;
$sub_level_2_counter = 0;
$sub_level_3_counter = 0;
foreach ($data as &$top_level)
{
$top_level['top_level_id'] = $top_level_counter++;
foreach($top_level as &$sub_level_1)
{
sub_level_1['sub_level_1_id'] = $sub_level_1_counter++;
foreach($top_level as &$sub_level_1)
{
sub_level_2['sub_level_2_id'] = $sub_level_2_counter++;
// and continue with the last level..
}
}
}
But as the example above, the keys can be empty ("") or even null because that’s data from the database.
I end up getting errors related to invalid values, but I can’t find out which.
I did figure that as I go inside each level, I have to check for:
if (is_array($sub_level_<x>)
because on each level above I already store the unique id which is not an array. But still, even with that, I get invalid input for foreach for example.
But I can’t find out what’s causing that, though I suspect it might be because of a null or empty value
Is there a better way to do that?
The reason I want to do it is to have an easier to work with identifier for each element in the array because the actual data is strings in another language.
Expected result would be:
$data = [
"" => [
'top_level_id' => 0,
'sub_level_1' => [
'sub_level_1_id' => 0,
'sub_level_2' => [
'sub_level_2_id' => 0,
'sub_level_3' => [
0 => ""
1 => "val"
]
]
]
],
"top_level_2" => [
'top_level_id' => 1,
'sub_level_1' => [
'sub_level_1_id' => 1,
'sub_level_2' => [
'sub_level_2_id' => 1,
'sub_level_3' => [
0 => ""
1 => "some_val"
2 => "foo"
]
]
]
]
];