我正在尝试向数组中添加一个元素,但是我得到了一个奇怪的输出。代码如下:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
我得到的输出是:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
虽然我需要的是FID在$names
数组中,所以它更像是:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
答案 0 :(得分:2)
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
答案 1 :(得分:1)
您可以使用<{1}}代替
array_push()
如果您使用$arrayname[indexname] = $value;
array_push()
<?php $array[] = $var; ?>
最好使用
Note: If you use `array_push()` to add one element to the array it's
,因为这样就没有开销 调用一个函数。$array[] =
已创建。
答案 2 :(得分:0)
针对特定问题的解决方案是在单个查询中选择所有必要的数据,无需向任何阵列添加元素。这是以下列方式完成的:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);