Skip to content
Advertisement

select column value from row by column index – laravel php

I want to select column value from a row by column index. I am trying to fetch data from a mysql database by using laravel php framework. I am able to select column value by its name but I didn’t find a way to select by column index.

<?php
    namespace AppHttpControllers;
    
    use IlluminateHttpRequest;
    
    use IlluminateSupportFacadesDB;
    
    class HomeController extends Controller
    {
        public function sample_name()
        {
            $page_title = 'Page1';
            $page_description = 'Some description for the page';
            
            $action = __FUNCTION__;
    
            $table = DB::select("my select query");
    
            foreach ($table as $value) {

               // I want to select first column value from this row
               $first_column_value = .....

            }
    
            return view('home.page', compact('page_title', 'page_description','action'));
        }
    }

Advertisement

Answer

why you can’t access with index because $value is associative array, to access by index you can use array_value($array) which return the index array

foreach($table as $value){
  $value=array_values((array)$value);
  $first_column_value =$value[0];
  $second_column_value =$value[1];
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement