duanluanlang8501 2015-09-23 11:27
浏览 50

尽管key不是字段名称,但是以密钥=>值格式获取MYSQL结果

(I really just need some MYSQL magic, but I will explain a bit more of what I am doing)

I am building a translation system. I know one way would be to create a translations table for each of my content types. For example if I had a table for Posts then I would have a separate table for Post translations:

tbl posts
----------
id
title
content

tbl posts_translations
---------
id
title
content
locale

And then if I did a LEFT join and get the results with PHP I would get all data I want as key=>value pairs, and I can use in my application as $row['p_title']

Because I will have multiple content types to translate and rather than maintaining field names in this way, can I achieve the same result with one?

i.e.

tbl translations
--------------------
id
type      i.e 'posts'
type_id   i.e. posts.id
key       i.e. 'content', 'title'
value     i.e. 'this is a title'
locale

So to get all the translations keys for a single post, I would:

SELECT key, value FROM translations 
WHERE type = 'posts' 
AND type_id = 3

This would give me a result set like:

$row = array(
  'key' => 'title',
  'value' => 'This is a title'
)

But what I want is:

$row['title'] => 'This is the title'

Of course I could do a PHP loop to format the data, but is there something in MYSQL that will present this data for me without the overhead of looping each result?

NOTE

I would like the resulting array keys to be generated from the column/field value, not the column/field name.

  • 写回答

1条回答 默认 最新

  • dougang1605 2016-06-29 21:35
    关注

    There is no single step way to do it.

    Write yourself a subroutine something like

    // Given an array of arrays (not ASSOC), use the first column as "key"; second as "value"
    function KeyValue($rows)
    {
        $kv = array();
        foreach ($rows as $row)
        {
            $kv[$row[0]] = $row[1];
        }
        return $kv;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line