Convert multidimensional array to single array in Laravel

Updated 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