【问题标题】:How do i change the column names in a result set and create a new result set in PHP with modified column names如何更改结果集中的列名并在 PHP 中使用修改后的列名创建新结果集
【发布时间】:2011-07-21 07:28:53
【问题描述】:

示例:我当前的结果集:

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"}

我想要一个新的结果集:

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"}

我不希望这影响我数据库中的列名。只有结果集。

【问题讨论】:

  • 结果是数组改变数组不会影响你的数据库。

标签: php names


【解决方案1】:

向我们展示您的查询。例如,如果您正在执行以下查询:

SELECT class_id, class FROM table;

改成这样:

SELECT class_id AS new_id, class AS new_class FROM table;

在查询中更改它是最好的方法,因为您不必在 PHP 中做任何额外的工作,当然您也可以在 PHP 中修改它们。

// where $resultset is your original results..
foreach ($resultset as &$result) {
    $result_ = array('new_id' => $result['class_id'], 'new_class' => $result['class']);
    $result = $result_;
}

请注意,这些方法都不会影响您的数据库列。唯一的方法是通过ALTER|MODIFY TABLE 声明。

【讨论】:

  • 当我 var_dump 我的新结果集时,我只得到 { ["new_id"]=>string(1) "3"["new_class"]=>string(3)"3rd"} 。但是 { ["new_id"]=>string(1) "1"["new_class"]=>string(3)"1st"} { ["new_id"]=>string(1) "2"["new_class" ]=>string(3)"2nd"} 不见了..!
  • @Rahul_2289 用什么方法?使用查询变体。
  • @rudi_visser: php 方法!
  • @Rahul_2289 试试查询方法,比 PHP 方法好 1000%。你确定你是var_dumping $resultset 而不是$result
【解决方案2】:

试试这个

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);

【讨论】:

    【解决方案3】:

    在 foreach 循环中。使用现有结果集中的列创建一个新数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多