所以我有一个对象,它成功地从数据库中提取所有行并存储它们,如下所示:
Object {models: Array[2]}
[Object, Object]
0: Object
address: "1234 Cooper"
firstname: "Rick"
lastname: "Bross"
address: "1234 Cooper"
__proto__: Object
我如何重组这个,所以我可以说:
alert(potentialModels.rickbross.firstname)
//rickbross = *whatever model i want to find*
并输出:
"Rick"
以下是我目前正在创建此对象的方式:
<?php
if($_SESSION['username']) {
$result = mysql_query("SELECT * FROM `potentials`") or die(mysql_error());
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = $r;
}
// now all the rows have been fetched, it can be encoded
$myJSON = json_encode(array('models' => $rows));
?>
以及我如何在控制台中获取它:
var potentialModels = <?php print($myJSON); ?>;
console.log(potentialModels);
答案 0 :(得分:0)
变化:
$rows[] = $r;
要:
$rows[strtolower($r['firstname'].$r['lastname'])] = $r;
你可以使用:
alert( potentialModels.models.rickbross.firstname);
如果您要删除models
,请停止将其添加到您的JSON:
json_encode(array('models' => $rows));
将其更改为:
json_encode( $rows);