执行获取查询后,我得到一个结果数组:
[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
)
)
如何获得这样的结果数组?:
[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
答案 0 :(得分:3)
直接来自SQL查询是不可能的:但您可以检索所有数据,然后重新映射数组
使用PHP 5.5的array_column(),您可以执行以下操作:
$myarray['row_choice'] = array_combine(
array_column($myarray['row_choice'], 'id'),
$myarray['row_choice']
);
对于早期版本的PHP,请使用array_map()代替
$myarray['row_choice'] = array_combine(
array_map(
function($value) {
return $value['id'];
},
$myarray['row_choice']
),
$myarray['row_choice']
);
答案 1 :(得分:1)
您应该创建一个新的数组变量,如下所示。
$recArr = array();
while ($records = mysqli_fetch_array($query)) {
$recArr[$records['id']] = $records;
}
var_dump($recArr);
祝你好运。