1

所以我有一个对象,它成功地从数据库中提取所有行并像这样存储它们:

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);
4

1 回答 1

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);
于 2013-04-14T16:46:13.343 回答