获取数据主键值作为关联数组的索引 [英] fetch data primary key value as the index for the associative array

查看:57
本文介绍了获取数据主键值作为关联数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行获取查询后,我得到一个结果数组:

After executing a fetch query I get a result array:

[row_choice] => Array
  (
    [0] => Array
      (
        [id] => 277410
        [text_value] => Two Wheel
      )
    [1] => Array
      (
        [id] => 277411
        [text_value] => Three Wheel
      )
    [2] => Array
      (
        [id] => 277412
        [text_value] => Four Wheel
      )
  )

如何获得这样的结果数组?:

How can I get a result array like this?:

[row_choice] => Array
  (
    [277410] => Array
      (
        [id] => 277410
        [text_value] => Two Wheel
      )
    [277411] => Array
      (
        [id] => 277411
        [text_value] => Three Wheel
      )
    [277412] => Array
      (
        [id] => 277412
        [text_value] => Four Wheel
      )
  )

我该怎么办?

我的查询是

SELECT id,text_value FROM answer_choice

推荐答案

不可能直接从SQL查询中获取:但是您可以检索所有数据,然后重新映射数组

It isn't possible directly from the SQL query: but you can retrieve all your data, then re-map the array

使用PHP 5.5的 array_column(),您可以做类似的事情:

Using PHP 5.5's array_column() you can do something like:

$myarray['row_choice'] = array_combine(
    array_column($myarray['row_choice'], 'id'),
    $myarray['row_choice']
);

否则,对于早期版本的PHP,请使用 array_map()代替

else for earlier versions of PHP, use array_map() instead

$myarray['row_choice'] = array_combine(
    array_map(
        function($value) {
            return $value['id'];
        },
        $myarray['row_choice']
    ),
    $myarray['row_choice']
);

这篇关于获取数据主键值作为关联数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆