skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 ...

    $a = is_string($a) ? trim(strip_tags($a)):$a;
    $b = is_string($b) ? trim(strip_tags($b)):$b;
    $c = is_string($c) ? trim(strip_tags($c)):$c;
    

    //Associative indices now working as expected


  2. 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

    var_dump($new_array[1]) // wont work
    var_dump($new_array['ca']) // will work
    

    Indexed arrays uses numeric values, just like a regular array would

    Accessing your new array, we could:

    foreach ($new_array as $key => $value) {
        var_dump($new_array[$key]);
    }
    

    I do not know if it would be useful but we can force an index array implementation using $array[] = ..

    $new_new_array = [];
    foreach ($new_array as $data) {
        $new_new_array[] = $data;
    }
    var_dump($new_new_array[1]); // this works
    

    I can only manage to do this at the very end because your data processing requires the keys to be strings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search