无法解析 sphinx/php 中的匹配结果

Unable to parse matching results in sphinx/php

如何在 php

中解析下面由 sphinx 返回的数组

php代码

if ( $result === false ) {
      echo "Query failed: " . $cl->GetLastError() . ".\n";
  }
  else {
      if ( $cl->GetLastWarning() ) {
          echo "WARNING: " . $cl->GetLastWarning() . "<br>";
      }

        if ($result['0'] > 0) {
            // print_r($result['0']['attrs']);   
            $words[] = $result['0']['matches'];
            foreach ($words as $val) {
                echo "=> " . $val['keyword'] . $val['ref'];
            }     
        } else {
                echo 'No results found';        
        }
  }

Array
(
    [0] => Array
        (
            [error] => 
            [warning] => 
            [status] => 0
            [fields] => Array
                (
                    [0] => keyword
                    [1] => ref
                )

            [attrs] => Array
                (
                    [keyword] => 7
                    [ref] => 7
                )

            [matches] => Array
                (
                    [25367434949034415] => Array
                        (
                            [weight] => 1643
                            [attrs] => Array
                                (
                                    [keyword] => hunting
                                    [ref] => activity
                                )

                        )

                )

            [total] => 1
            [total_found] => 1
            [time] => 0.000
            [words] => Array
                (
                    [hunt] => Array
                        (
                            [docs] => 1
                            [hits] => 1
                        )

                )

        )

)

我想解析 'matches' 数组及其子数组值,如关键字、引用等

让我们专注于这一点

    if ($result['0'] > 0) {
        $words[] = $result['0']['matches'];
        foreach ($words as $val) {
            echo "=> " . $val['keyword'] . $val['ref'];
        }
    }

首先,结果不是一个整数,所以不应该真正作为一个进行比较(尽管猜测它可能有效)

个人建议检查实际匹配 - 并使用空,这在数组上工作得很好...

    if (!empty($result['0']['matches'])) {

然后你出于某种原因将匹配 添加到 数组(这就是 $arry[] = 所做的,它有效地 'push')

...但也没有分配给变量的点,因为它只使用一次(在 foreach 中)

... 另外,通常 document_id 是 matches 数组的索引,所以公开它。

        foreach ($result['0']['matches'] as $doc_id => $val) {

终于,现在有了匹配项,想要 attors 数组中的属性。所以像

            $a = $val['attrs'];
            echo $doc_id." => ".$a['keyword'].", ".$a['ref']."<br>\n";

把它们放在一起...

    if (!empty($result['0']['matches'])) {
        foreach ($result['0']['matches'] as $doc_id => $val) {
            $a = $val['attrs'];
            echo $doc_id." => ".$a['keyword'].", ".$a['ref']."<br>\n";
        }
    }