Search code examples
phpnames

How do i change the column names in a result set and create a new result set in PHP with modified column names


Example: my current result set:

array(7) {[0]=>array(2) 

{ ["class_id"]=>string(1) "1"["class"]=>string(3)"1st"}

{ ["class_id"]=>string(1) "2"["class"]=>string(3)"2nd"}

{ ["class_id"]=>string(1) "3"["class"]=>string(3)"3rd"}

I want a new result set as :

array(7) {[0]=>array(2) 

{ ["new_id"]=>string(1) "1"["new_class"]=>string(3)"1st"}

{ ["new_id"]=>string(1) "2"["new_class"]=>string(3)"2nd"}

{ ["new_id"]=>string(1) "3"["new_class"]=>string(3)"3rd"}

I dont want this to affect the column names in my database. only the result set.


Solution

  • try this

    function rename_key(&$array, $oldkey, $newkey) {
    // remember here we send value by reference using `&`
        if(array_key_exists($oldkey,$array))
        {
            $array[$newkey] = &$array[$oldkey];
            unset($array[$oldkey]);
        }
        return $array;
    }
    
    foreach($input as $k)
    {
        rename_key($k, 'class_id', 'new_id');
        rename_key($k, 'class', 'new_class');
        $output[]=$k;
    }
    echo "<pre>";
    print_r ($output);