数组以随机方式获取PHP

时间:2015-10-11 16:21:43

标签: php arrays random

在我的$data数组中,我存储了一些数据。因此,当我尝试搜索正确方向的东西时,我的函数可以在数组中找到。

例如---

Suppose i am looking for **Samsung Galaxy S** from my array $data, 
it will return the value 1, 2 and 4 from the array

但问题是我想以随机的方式在数据中找到。 喜欢 - " S Galaxy Samsung"

但数据存储如同 - Samsung GT-i9100 Galaxy S II 所以当我搜索"三星Galaxy S" 时,它实际上找到了价值。 但是当我搜索' S Galaxy Samsung' 时,它无法找到该值,因为我们是以随机方式找到的。

但它应该在数组中找到,因为请求数据就在那里。

任何人都知道这个问题的任何解决方案!!!!

   function fetchDataAction() {
    $_POST = 'S Galaxy Samsung';
    $search = $this->my_array_search($data, $_POST); // $data is the array
   } 

function my_array_search($array, $string) {
    $pattern = preg_replace('/\s+/', ' .*', preg_quote($string));
    return array_filter($array, function ($value) use($pattern) {
        return preg_match('/' . $pattern . '/', $value) == 1;
    });
}


$data =
Array
(
    [0] => Array
        (
            [name] => Samsung GT-N7100 Galaxy Note II 16GB
        )

    [1] => Array
        (
            [name] => Samsung GT-i9100 Galaxy S II
        )

    [2] => Array
        (
            [name] => Samsung GT-i9300 Galaxy S III 16GB
        )

    [3] => Array
        (
            [name] => Apple iPhone 5 16GB
        )

    [4] => Array
        (
            [name] => Samsung GT-P5110 Galaxy S 4 10.1 16GB
        )

    [5] => Array
        (
            [name] => Samsung UE46ES6715
        )

    [6] => Array
        (
            [name] => Samsung 830 Series MZ-7PC128 128GB
        )

    [7] => Array
        (
            [name] => Samsung GT-N8000 Galaxy Note 10.1 16GB
        )

    [8] => Array
        (
            [name] => Samsung 830 Series MZ-7PC256 256GB
        )

    [9] => Array
        (
            [name] => Samsung UE46ES6715
        )

    [10] => Array
        (
            [name] => Samsung GT-2423 Galaxy Tab 4 10.1 16GB
        )

1 个答案:

答案 0 :(得分:4)

像elasticsearch,lucene或sphinx这样的文本搜索工具可能更适合大规模应用。

如果你想使用PHP,下面的脚本将逐字逐句地进行,并返回包含所有单词的$ data中第一行的索引。重复单词只计算一次。如果未找到匹配项,则返回-1。

function my_array_search($dataArray, $searchWords) {

    $searchWords=array_flip(explode(' ', $searchWords));
    $targetScore = count($searchWords);

    foreach($dataArray as $index=>$data) {

        $words=array_unique(explode(' ', $data['name']));
        $score = 0;

        foreach($words as $word) {
            if(isset($searchWords[$word])) ++$score;
        }

        if($score >= $targetScore) {
            return $index;
       }
    }
    return -1;
}

示例用法是

$matchId = my_array_search($data, 'S Galaxy Samsung'); 

Returns $matchId=1; // this is the first row in the sample data to contain all those words.

它不是最佳解决方案,因为它可能无法扩展或处理拼写错误等边缘情况。但是,您可以将其调整为适合直接使用的工作。