获取数据主键值作为关联数组的索引
fetch data primary key value as the index for the associative 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
)
)
如何获得这样的结果数组?:
[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 查询:但您可以检索所有数据,然后重新映射数组
使用 PHP 5.5 的 array_column() 你可以这样做:
$myarray['row_choice'] = array_combine(
array_column($myarray['row_choice'], 'id'),
$myarray['row_choice']
);
else 对于 PHP 的早期版本,使用 array_map() 代替
$myarray['row_choice'] = array_combine(
array_map(
function($value) {
return $value['id'];
},
$myarray['row_choice']
),
$myarray['row_choice']
);
您应该创建一个新的数组变量,如下所示。
$recArr = array();
while ($records = mysqli_fetch_array($query)) {
$recArr[$records['id']] = $records;
}
var_dump($recArr);
祝你好运。
执行提取查询后,我得到一个结果数组:
[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
无法直接从 SQL 查询:但您可以检索所有数据,然后重新映射数组
使用 PHP 5.5 的 array_column() 你可以这样做:
$myarray['row_choice'] = array_combine(
array_column($myarray['row_choice'], 'id'),
$myarray['row_choice']
);
else 对于 PHP 的早期版本,使用 array_map() 代替
$myarray['row_choice'] = array_combine(
array_map(
function($value) {
return $value['id'];
},
$myarray['row_choice']
),
$myarray['row_choice']
);
您应该创建一个新的数组变量,如下所示。
$recArr = array();
while ($records = mysqli_fetch_array($query)) {
$recArr[$records['id']] = $records;
}
var_dump($recArr);
祝你好运。