Search code examples
phpjsonzend-framework2

Zend2 read all JSON files content and return results to view


I have been struggling the last 2 days to make this work but I cannot get to the bottom of it. I need to read all the .json files from a folder and get back the result so I can make my "statistics" which are stored in those .json files.

If I use print_r(); in the controller, I get arrays with the content from the files, which is exactly what I want, but when I want to pass it to the view, I get only 1 array, and that is the first, no matter what I tried. I also tried returning with JsonModel() but no success, I get the same result.

This is the function I tried using to read the files and hopefully get back the result:

public function getJSONAction(){
        
        $my_array_data = array();
        
        //$reader = new \Zend\Config\Reader\Json();
         
        //$data   = $reader->fromFile('./data/tti/video.json');
         
        $files = glob('./data/stats/*.{json,txt}', GLOB_BRACE);

        foreach($files as $file) {
                
            //$data = array($reader->fromFile($file));
                
            $data  =  file_get_contents($file);
                
            $my_array_data = json_decode($data, TRUE);

            $view = new JsonModel ( array(
            
                    'my_array_data' => $my_array_data
            ));
        }
        
        $view->setTerminal(true);
        
        return $view;
    }

I tried many ways, but I still cannot make it work, can someone please point me to the right direction? Or some example would be even more helpful.

Thank you.

EDIT:

I got it working... it was my stupid mistake, I should have put ** $my_array_data[] **

Thank you for trying to help.


Solution

  • Maybe try once like this:

    public function getJSONAction(){
    
        $my_array_data = array();
    
        $reader = new \Zend\Config\Reader\Json();
    
        $files = glob('./data/stats/*.{json,txt}', GLOB_BRACE);
    
        foreach($files as $file) {
    
            $data = array($reader->fromFile($file));
    
            $data = file_get_contents($file);
    
            $my_array_data = array_merge( $my_array_data, json_decode($data, TRUE));
    
        }
    
        $view = new JsonModel ( array(
    
            'my_array_data' => $my_array_data
        ));
    
        $view->setTerminal(true);
    
        return $view;
    }
    

    The main difference is merging the different data arrays into one and then returning the merged result in a JsonModel.