I’m not sure how to describe or even title this issue but I feel the psuedo code explains it well. I have a multidimensional array called $data (4 levels) and some php code as follows:
$data = [
'a'=>['b'=>['c'=>['text','text','text'],
'ca'=>['1','1.5','2']
],
'ba'=>['c'=>['text','text','text'],
'ca'=>['1','1.5','2']
]
],
'a1'=>['b'=>['c'=>['text','text','text'],
'ca'=>['1','1.5','2']
],
'ba'=>['c'=>['text','text','text'],
'ca'=>['1','1.5','2']
]
],
];
$new_array = [];
foreach($data as $a=>$bs){
foreach($bs as $b=>$cs){
foreach($cs as $c=>$d){
$new_array[$c][$b][$a] = $d;
}
}
}
//I don't know why ...
print_r($new_array);//works, including indices
print_r($new_array['known_index']);//displays nothing, no errors or warnings
print_r($new_array[0]);//displays nothing, no errors or warnings
print_r(current($new_array));//works
I tried enclosing the index variables in double quotes and I have worked around the problem overall. I just don’t know what’s going on and it feels like I should. PHP 8.2
2
Answers
Turns out this question should be moved to Data Science or similar. The problem was the web scrape. Hidden HTML tags were breaking the indices. Since the array is built in so many places, from so many sources it's easiest, (not optimal) to fix it in situ ...
//Associative indices now working as expected
PHP associative and indexed arrays are different.
Associative arrays uses named keys — strings, to access the variable data. Your code generates an associative array, so using
Indexed arrays uses numeric values, just like a regular array would
Accessing your new array, we could:
I do not know if it would be useful but we can force an index array implementation using $array[] = ..
I can only manage to do this at the very end because your data processing requires the keys to be strings.