我正在尝试从mysql查询创建多维数组。该阵列深3层。每个用户都有一个membershipid,该会员ID可以具有多个字符ID。每个这些角色ID可以具有多个属性。
membershipid-> characterid(最多3个)->轻,种族。
$query = "SELECT p.membershipid, p.displayname, c.characterid, c.light, c.racehash
FROM Players as p
LEFT JOIN Characters as c
ON c.membershipid = p.membershipid";
$result = $mysqli->query($query) or die("SQL Error: Members konden niet worden opgehaald.");
// Loop through the requested data, add to an array
while ($data = mysqli_fetch_assoc($result)) {
$categorylist[ $data['membershipid'] ] = array(
'displayname' => $data['displayname'],
array('characterid' => $data['characterid'],
'light' => $data['light'],
'racehash' => $data['racehash']
)
);
} // end while statement
// A test to see how many items in array
echo "<pre>\n";
print_r($categorylist);
echo "</pre>\n";
这有效,但每个人仅显示1个字符,而查询结果显示每个会员ID的每个字符ID。
Array
(
[4611686018428931875] => Array
(
[displayname] => White_Anomaly
[0] => Array
(
[characterid] => 2305843009264668680
[light] => 554
[racehash] => 3887404748
)
)
[4611686018437972738] => Array
(
[displayname] => Bpunisher7
[0] => Array
(
[characterid] => 2305843009277456739
[light] => 392
[racehash] => 2803282938
)
)
我可能对数组定义做错了,并且每次都覆盖我的characterid,因为我只获得了最新的characterid。
首选数组=
Array
(
[4611686018428931875] => Array
(
[displayname] => White_Anomaly
[characters] => Array
(
[0] => Array
(
[characterid] => 2305843009264668678
[light] => 370
[racehash] => 3887404748
)
[1] => Array
(
[characterid] => 2305843009264668680
[light] => 554
[racehash] => 3887404748
)
)
)
[4611686018437972738] => Array
(
[displayname] => Bpunisher7
[characters] => Array
(
[0] => Array
(
[characterid] => 2305843009265241161
[light] => 534
[racehash] => 2803282938
)
[1] => Array
(
[characterid] => 2305843009265241163
[light] => 524
[racehash] => 3887404748
)
[2] => Array
(
[characterid] => 2305843009277456739
[light] => 392
[racehash] => 3887404748
)
)
)
)
答案 0 :(得分:1)
如果您允许我稍微重组结果数组,这应该是更好的方法:
// Loop through the requested data, add to an array
while ($data = mysqli_fetch_assoc($result)) {
extract($data,EXTR_PREFIX_ALL,'data');
$categorylist[$data_membershipid]['displayname'] = $data_displayname;
$categorylist[$data_membershipid][$data_characterid] = ['light' => $data_light,
'racehash' => $data_racehash];
} // end while statement
如您所见,我已经将'characterid'移到了子数组的键上。这样做是为了避免覆盖其他字符。
我还对数组使用了新的表示法。 extract()
只是为了使代码更易于阅读,但您可以摆脱它。
也许最好将字符放在自己的数组中,如下所示:
// Loop through the requested data, add to an array
while ($data = mysqli_fetch_assoc($result)) {
extract($data,EXTR_PREFIX_ALL,'data');
$categorylist[$data_membershipid]['displayname'] = $data_displayname;
$categorylist[$data_membershipid]['characters'][$data_characterid] = ['light' => $data_light,
'racehash' => $data_racehash];
} // end while statement
答案 1 :(得分:0)
如果$ categorylist [$ data ['membershipid']]存在,那么下一个字符将覆盖它。
您必须检查$ categorylist [$ data ['membershipid']]是否存在。在这种情况下,请使用array_push()添加第二个字符。否则您的代码仍然有效。