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.
Show us your query.. If you're doing, for example, the following query:
SELECT class_id, class FROM table;
Change it to this:
SELECT class_id AS new_id, class AS new_class FROM table;
Changing it in the query is hands-down the best way to do it, as you're not having to do any extra work within PHP, however you could also amend them in PHP, of course.
// where $resultset is your original results..
foreach ($resultset as &$result) {
$result_ = array('new_id' => $result['class_id'], 'new_class' => $result['class']);
$result = $result_;
}
Note that neither of these methods would affect your database columns. The only way to do that would be via an ALTER|MODIFY TABLE
statement.
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);
In foreach cycle. Create a new array with needed to you colums from existing result set.
精彩评论