在如何将php数组转换为JSON对象时,我遇到了问题。无论我如何尝试,我要么将所有内容打印为多个对象,要么将其作为null.Wrapping在pre tags中显示出来,下面是我得到的最接近的结果:
我的代码:
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
echo "<pre>";
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}
echo "</pre>";我的产出:
{"0":"John Apple","title":"John Apple","1":"Apple","lastname":"Apple"}
{"0":"Kumar Patel","title":"Kumar Patel","1":"Patel","lastname":"Patel"}
{"0":"Michaela Quinn","title":"Michaela Quinn","1":"Quinn","lastname":"Quinn"}
{"0":"Peyton Manning","title":"Peyton Manning, MD","1":"Manning","lastname":"Manning"}
{"0":"John Doe","title":"John Doe","1":"Doe","lastname":"Doe"}
{"0":"Jane Lee","title":"Jane Lee","1":"Lee","lastname":"Lee"}
{"0":"Dan McMan","title":"Dan McMan","1":"McMan","lastname":"McMan"}
{"0":"Yu Win","title":"Yu Win","1":"Win","lastname":"Win"}我的两个问题是:
1)为什么有一个"0":"John Apple"和一个"1":"Apple",而我只想要对象中的"title":"John Apple"和"lastname":"Apple"?
2)为什么所有东西都以多个对象的形式显示?
谢谢!
--编辑--
$arr = array()
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print $arr;
echo "</pre>";发布于 2014-01-09 19:47:45
field_last_name是您的表名吗?您能否根据查询中的revision.title这样的表名来区分每个列名前缀,然后在一个数组中获取所有数据,然后json_encode它呢?
$content = mysqli_query($dbcon,
"SELECT title, last_name AS lastname
FROM revision, field_last_name
WHERE vid = entity_id;"
);
$arr = array();
echo "<pre>";
while($row = mysqli_fetch_assoc($content))
{
$arr[] = $row;
}
print_r(json_encode($arr));
echo "</pre>";发布于 2014-01-09 19:45:22
改变这一点:
while($row = mysqli_fetch_array($content))
{
print json_encode($row);
print '<br/>';
}对此:
$row = mysqli_fetch_assoc($content);
json_encode($row);发布于 2014-01-09 19:46:42
...because,您正在打印多个对象。如果您想要一个单独的对象,即数组,则需要将mysql_fetch_assoc的结果(请参阅涵盖字段名和位置的其他答案)附加到数组中,然后一次性地将数组添加到json_encode。示例:
$myarray = array();
while($row = mysqli_fetch_assoc($content))
{
$myarray[] = $row;
print '<br/>';
}
print json_encode($myarray);https://stackoverflow.com/questions/21029634
复制相似问题