1

我有一个包含单词列表的数组:

myArray = array(first, time, sorry, table,...);

和一个 JSON :

{
    "products": {
        "0": {
            "title": "myTitle",
            "url": "xxxxxx",
            "id": "329102"
        },
        "1": {
            "title": "myTitle",
            "url": "",
            "id": "439023",
        },...
     }
}

我做了一个循环,如果标题包含 myArray 的单词之一,我显示它。

    function strposArray($haystack, $needle, $offset=0) {
        if(!is_array($needle)) $needle = array($needle);
        foreach($needle as $query) {
            if(stripos($haystack, $query, $offset) !== false) return true;
        }
        return false;
    }



    foreach ( $parsed_json['products'] as $item ) {

        if (!empty($item['title'])) { $title = $item['title']; } else { $title = ''; }


        if ( strposArray($title, $myArray) ) {

            echo '<li>' .$title. '</li>';

        }

    }

我对这段代码没有任何问题,但我想改进结果。

如果标题包含 myArray 的多个元素,我希望它出现在列表的顶部。

第一个 -> 多个元素

第二个 -> 一个元素

先感谢您

4

1 回答 1

0

此功能应该完全符合您的要求:

function sortByWords(array $words, array $products){
    $results = [];
    foreach($products as $product){
        $elementCount = 0;
        foreach($words as $word){
            if(stripos($product['title'], $word) !== false){
                $elementCount++;
            }
        }

        if($elementCount > 0){
            $results[] = ['elementCount' => $elementCount, 'product' => $product];
        }
    }

    usort($results, function($a, $b){
        return $a['elementCount'] < $b['elementCount'];
    });

    return $results;
}

尝试var_dump函数的结果。结果数组看起来像这样:

C:\Users\Thomas\Projects\file.php:28:
array (size=3)
  0 => 
    array (size=2)
      'elementCount' => int 3
      'product' => 
        array (size=1)
          'title' => string 'Apple Orange Peach' (length=18)
  1 => 
    array (size=2)
      'elementCount' => int 2
      'product' => 
        array (size=1)
          'title' => string 'Apple Orange' (length=12)
  2 => 
    array (size=2)
      'elementCount' => int 1
      'product' => 
        array (size=1)
          'title' => string 'Peach' (length=5)

这是您访问结果的方式。

$results = sortByWords($words, $products);
foreach($results as $result){
    $product = $result['product'];

    // now you can access your title, url and id from the $product array.
    echo $product['title'];

    // if you need the number of elements in the title, you can use $result['elementCount']
}
于 2017-01-31T16:23:30.860 回答