Search code examples
phparrayscodeigniter

How do I change the name of the key in an array?


I've seen many posts answering this question in various forms, but somehow none seem to quite solve my problem.

PHP 5.5.8 + CodeIgniter

The complete picture:

A SQL query produces an array of department names.

$strSQL = "SELECT DISTINCT DepartmentName FROM ...
$query=$this->db->query($strSQL);
$data=$query->result_array();

I flatten the array to make it really simple.

$flatArray = array_column($data, 'DepartmentName');
array_unshift($flatArray, "");
return $flatArray;

And then return in to my controller to create the drop downbox on the form.

The array however is of the form:

[PGroups] => Array
                    (
                        [0] => Dept 1
                        [1] => Dept 2
                        [2] => Dept 3
                         .....

And in my (CodeIgniter based) view, I have this:

`echo "<td>" .  form_dropdown('PurchasingGroup', $PGroups). "</td>";`

which creates the HTML dropdown list with numerical values as the options, and not the actual words of the department titles.

I'm trying to get this result:

["Dept 1"] => Dept 1
["Dept 2"] => Dept 2
["Dept 3"] => Dept 3
.....

..because then when I buyild my view, the value options will be the exact text to put into my SQL search to retrieve further info.

To solve this I've tried

  • doing something in the SQL statement, but that can't influence the key names - dead end
  • then one post said to try this, but I don't understand how that changes the key name, it seems to just change the value of the element.

    $arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]);

It's staring me in the face, but I'm going round in circles. Help?


Solution

  • To replace old array values you have to perform a very simple command:

    $arr = array_combine( $arr, $arr );
    print_r( $arr );
    

    Will output:

    Array
    (
        [Dept 1] => Dept 1
        [Dept 2] => Dept 2
        [Dept 3] => Dept 3
    )
    

    3v4l.org demo