php JSON输出的结构

时间:2010-10-27 13:49:21

标签: php ajax json forms

这是我提出的另一个问题: Listing out JSON data?

我的搜索只返回1项,我很确定问题出在我的PHP的某个地方,我不太确定如果我正确地添加到数组,或者它可能是你可以在上面的链接上看到的javascript,但我怀疑它。

我的PHP代码:


function mytheme_ajax_response() {
  $search = $_GET["search_text"];
  $result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);

  $noder = array();
  while ($record = db_fetch_object($result)) {
 $noder[] = $record;
  }

  $matches = array();
 $i = 0;
  foreach ($noder as $row) {
    $node = node_load($row->nid);
    $termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
    $matches[$i]['title'] = $node->title;
 $matches[$i]['link'] = $termlink->tid;
  }
 ++$i;
 $hits = array();
 $hits['matches'] = $matches;
  print json_encode($hits);
  exit();
}

2 个答案:

答案 0 :(得分:2)

在foreach循环之后,您似乎正在递增$ i变量。因此,$ i在整个循环中始终为0,因此您始终为$ matches [0]设置标题和链接值。

答案 1 :(得分:0)

试试这个:

function mytheme_ajax_response() {
  $search = $_GET["search_text"];
  $result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);

  $noder = array();
  while ($record = db_fetch_object($result)) {
 $noder[] = $record;
  }

  $matches = array();
  foreach ($noder as $row) {
    $node = node_load($row->nid);
    $termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
    $matches[] = array('title' => $node->title, 'link' => $termlink->tid);
  }
 $hits = array();
 $hits['matches'] = $matches;
  print json_encode($hits);
  exit();
}

$ i没有增加代码,因为它在foreach循环之外。通过制作如上所述的第二个阵列,你无论如何都不需要它......(希望这有效)......