使用PHP将Mysql关联数组中的键更改为人类可读键

时间:2013-12-15 03:56:57

标签: php mysql

我有两个mysql表,一个存储有关用户的数据,如

  user_id | user_name |  user_email_address
     1    |  john232  |  john232@someemail.com
     2    |  Lisa122  |  Lisa1232@someemail.com

第二个表是一个定义表,存储如下数据:

  table_id | table_name | table_column       | column_label
      1    | user       | user_name          | User Name 
      2    | user       | user_email_address | Email Address

最后我要完成的是从数据库中检索来自users表的数据,它看起来像这样。

   Array
  (
  [0] => Array
     (
        [user_id] => 1
        [user_name] => john232
        [user_email_address] => john232@someemail.com
    )

[1] => Array
    (
        [user_id] => 2
        [user_name] => Lisa122 
        [user_email_address] => Lisa1232@someemail.com
    )
  )

数据需要像这样转换:

   Array
  (
  [0] => Array
     (
        [User ID] => 1
        [User Name] => john232
        [Email Address] => john232@someemail.com
    )

[1] => Array
    (
        [User ID] => 2
        [User Name] => Lisa122 
        [Email Address] => Lisa1232@someemail.com
    )
  )

任何正确方向的帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:3)

你不需要PHP来做这件事 - 免除大量不必要的工作;您可以更改SQL以使用AS关键字来为列名设置别名。例如

SELECT user_id AS "User ID", user_name AS "User Name", user_email_address AS "Email Address" FROM user_table;

如果您想要计算您的计数等,这也很有用,例如:

SELECT count(*) AS "Total Users" FROM user_table;

Total Users
-----------
500

另一方面,你可能想要更多地考虑你的选择,在命名中使用带空格的关联键,只是超出惯例,这可能不是最好的做法。

答案 1 :(得分:1)

这是一个示例,您应该为自己的数据替换$data

<?
$data = array(
    array('user_id' => 1, 'user_name' => 'john232', 'user_email_address' => 'john232@someemail.com'),
    array('user_id' => 1, 'user_name' => 'john232', 'user_email_address' => 'john232@someemail.com'),
);
$humanReadable = array('user_id' => 'User ID', 'user_name' => 'User Name', 'user_email_address' => 'Email');
$restul = array();
foreach ($data as $row) {
    $newRow = array();
    foreach($row as $key => $value) {
        if(array_key_exists($key, $humanReadable)) {
            $newRow[$humanReadable[$key]] = $value;
        } else {
            $newRow[$key] = $value;
        }
    }
    $result[] = $newRow;
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>

这会产生:

Array
(
    [0] => Array
        (
            [User ID] => 1
            [User Name] => john232
            [Email] => john232@someemail.com
        )

    [1] => Array
        (
            [User ID] => 1
            [User Name] => john232
            [Email] => john232@someemail.com
        )

)