如何查询我的API以格式化结果,以便Typeahead可以使用它?

时间:2016-12-21 17:59:02

标签: javascript mysql arrays json typeahead.js

Typeahead需要我的JSON结果看起来像这样:

Array [
{"id": "5001", "email": "me@myself.com"},
{"id": "5002", "email": "you@yourself.org"},
{"id": "5003", "email": "them@anywhere.net"},
{"id": "5004", "email": "nobody@home.us"},
{"id": "5005", "email": "anyone@anytime.info"}, ...];

但是当我使用这个查询时:

    $sth = $this->pdo()->prepare(
        "SELECT * FROM advocates ;"
    );
    $result = $sth->execute();
    if( $result && $sth->rowCount() > 0 ) {
        while($row=$sth->fetch()) {
            $alladv_emails['id'] = $row['id'];
            $alladv_emails['email'] = $row['emailAddress'];
        }
    }
    echo json_encode($alladv_emails);

我只得到一个这样的结果:

Array ( [value] => cmyles97@yahoo.com [data] => 53930344 )

如何重新设计我的查询以格式化我的JSON,就像预期的那样?

另外,显然我希望获得超过1个结果。我认为它每次都会覆盖数组,这就是为什么我只得到1个结果。但是,当我尝试添加一个合格的数组时,它会使JSON复杂化。

我试过了:

        $alladv_emails[0]['id'] = $row['id'];
        $alladv_emails[0]['email'] = $row['emailAddress'];

它看起来像这样,而STILL只返回1行:

Array ( [0] => Array ( [value] => cmyles97@yahoo.com [data] => 53930344 ) ) 

最初我打算用这个:

            $alladv_emails[$row['id']] = $row['emailAddress'];

但是,我得到了这种类型的结果,但我确实得到了所有17000个结果,只是没有我想要的格式。

Array ( [40891510] => obfuscate@aol.com [40891511] => obfuscate@nobleharbor.com [40891512] => obfuscate@rochester.rr.com [40891513] => obfuscate@hotmail.com ...

新信息:

我在上一次php查询后添加了以下函数:

    $emailarray = array();
    $subarray = array();
    foreach ($session->getAllEmails() as $key => $val){
        $subarray = array('id' => $key, 'email' => $val);
        array_push($emailarray,$subarray);
    }

......现在我得到的东西非常接近我需要的东西:

    Array 
( [0] => Array 
    ( [id] => 40891510 
    [email] => obfuscate@aol.com ) 
[1] => Array 
    ( [id] => 40891511 
    [email] => obfuscate@nobleharbor.com ) 
[2] => Array (
    [id] => 40891512 
    [email] => obfuscate@rochester.rr.com )
...

几乎就在那里。它仍然无法正常输入。

0 个答案:

没有答案