Convert multidimensional array to single array in Laravel

Created at 24-Sep-2021 , By samar

Convert multidimensional array to single array in Laravel

Through the use of the programming language, we will work together to solve the "Convert multidimensional array to single array in Laravel" puzzle in this lesson.

You can convert multidimensional array to single array in Laravel.
  • Convert multidimensional array into single array

    //routes\web.php
    use App\Http\Controllers\HomeController;
    Route::get('/convert-array',[HomeController::class, 'multidimensionalToSingleArray']);
    
    //app\Http\Controllers\HomeController.php
    public function multidimensionalToSingleArray(){
        $myarray = array(
            array("Ankit", "Ram", "Shyam"),
            array("Unnao", "Trichy", "Kanpur")
        );
        $arrayData = $this->array_flatten($myarray);
        print_r($arrayData);
    }
    
    private function array_flatten($array) { 
        
        if (!is_array($array)) { 
            return FALSE; 
        } 
        $result = array(); 
        foreach ($array as $key => $value) { 
            if (is_array($value)) { 
                $result = array_merge($result, $this->array_flatten($value)); 
            } 
            else { 
                $result[$key] = $value; 
            } 
        } 
        return $result; 
    }
    

    Output :

    Array ( [0] => Ankit [1] => Ram [2] => Shyam [3] => Unnao [4] => Trichy [5] => Kanpur )

    Input data
    array(
            array("Ankit", "Ram", "Shyam"),
            array("Unnao", "Trichy", "Kanpur")
        );

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.