Convert multidimensional array to single array in Laravel

You can convert multidimensional array to single array in Laravel.

Answers 1
  • 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; 
    }
    
    0

    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