从数据库中获取结果,并为JSON enconde准备数组后,我面临着如何引用数组数据的困境'在主阵列内。
" [0]"到目前为止是我的逻辑错误......
while ($row =$result->fetch()) {
$name = $row['country'];
$id = $row['id']
$username = $row['username'];
$subtotal = $row['subtotal'];
if ( /* If $id exist in array row['series']}*/ ) {
///?????/////
/// Add array to 'DATA'
////?????////
$rows['series']["$id"]["$name"]['data'][]=array("$username", $subtotal);
}
else {
$rows['series'][]= array('id' => "$id", 'name' => "$name", 'data' => array("$username", $subtotal));
}
vardump显示如下:
array(1) {
["series"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_5"
[1]=>
string(5) "86040"
}
}
[1]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_8"
[1]=>
string(5) "20358"
}
}
}
}
但我想添加具有相同ID /名称的最后一项:
array(1) {
["series"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_5"
[1]=>
string(5) "86040"
}
array(2) {
[0]=>
string(17) "GK_8"
[1]=>
string(5) "20358"
}
}
}
}
答案 0 :(得分:0)
最自然的方法是稍微更改一下数据结构,以便series
数组由行ID而不是任意运行索引编制索引。这将允许您将循环重写为(使用mysqli语法作为示例):
$stmt->bind_result($id, $country, $username, $subtotal);
$series = array();
while ( $stmt->fetch() ) {
$series[$id]['country'] = $country;
$series[$id]['data'][] = array(
'username' => $username,
'subtotal' => $subtotal,
);
}
其中will give you数据结构如:
$series = array(
'hn' => array(
'country' => 'HN',
'data' => array(
0 => array(
'username' => 'GK_5',
'subtotal' => 86040
),
1 => array(
'username' => 'GK_8',
'subtotal' => 20358
),
// ...
)
),
// ...
);
如果您需要您帖子中显示的确切格式的数据,您当然可以使用foreach
对此数组进行转换以进行转换,例如:
$rows = array();
foreach ( $series as $id => $record ) {
$record['id'] = $id;
$rows['series'][] = $record;
}