Home > other >  Create Array With Key And Value Pair In Codeigniter 4
Create Array With Key And Value Pair In Codeigniter 4

Time:09-06

I am trying to create and array to fill for my form_dropdown() for my view:

<?php echo form_dropdown('vendor', $vendors, '', '') ?>

However, I am only getting the last value based on the function that generates the array:

public function get_vendors() {
        $vendors = $this->db->table('vendor')->get()->getResultArray();
        // Return key => value pair array
        $array = array(
            0 => 'Not Assigned'
        );
         
        if (!empty($vendors)) {
            foreach ($vendors as $vendor) {
                $array = array(
                    $vendor['id'] => $vendor['vendor']
                );
            }
        }
        
        return $array;
    }

This function is within my model. The only problem I have is that it's returning only the last row from the table. However when I do a var_dump() for the $vendors I get all the rows. Not sure what I am doing wrong.

array (size=2)
  0 => 
    array (size=4)
      'id' => string '1' (length=1)
      'vendor' => string 'Blue Chip' (length=9)
      'datecreated' => string '2022-08-16' (length=10)
      'datemodified' => string '2022-08-16' (length=10)
  1 => 
    array (size=4)
      'id' => string '2' (length=1)
      'vendor' => string 'ASP' (length=3)
      'datecreated' => string '2022-08-30' (length=10)
      'datemodified' => string '2022-08-31' (length=10)

CodePudding user response:

Changing the query to from getResultArray() to getResultObject() did the trick. So I was able to use $array[$vendor->id] = $vendor->vendor;

public function get_vendors() {
        $vendors = $this->db->table('vendor')->get()->getResultObject();
        // Return key => value pair array
        $array = array(
            0 => 'Not Assigned'
        );
         
        if (!empty($vendors)) {
            foreach ($vendors as $vendor) {
                $array[$vendor->id] = $vendor->vendor;
            }
        }
        
        return $array;
    }

CodePudding user response:

If you still want to use getResultArray():

public function get_vendors() {
    $vendors = $this->db->table('vendor')->get()->getResultArray();
    // Return key => value pair array
    $array = array(
        0 => 'Not Assigned'
    );
     
    if (!empty($vendors)) {
        foreach ($vendors as $vendor) {
             $array[$vendor['id']] => $vendor['vendor'];
        }
    }
    
    return $array;
}
  • Related