2012-12-07 19 views
1

我想檢查多維數組中的值是否與給定的百分比相同。將多維數組中的相應值和相同的百分比返回給定值。 (PHP)

例如,這是我的數組:

$shop = array(array(Title => "rose", 
         Price => 1.25, 
         Number => 15 
        ), 
       array(Title => "daisy", 
         Price => 0.75, 
         Number => 25, 
        ), 
       array(Title => "orchid", 
         Price => 1.15, 
         Number => 7 
        ) 
      ); 

,如果一個給定的值(比如說「testorchid」)是55%相同的多維陣列中的值。返回多維數組中相應的值和相同的值。

所以在這種情況下。如果我與「testorchid」檢查,它返回「蘭花」和55.56 procent。 像similar_text有點():工作

我可以檢查是否給定值(針)是一樣的多維數組中值的函數:

function in_array_r($needle, $haystack, $strict = true) { 
    foreach ($haystack as $item) { 
     if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { 
      return true; 
     } 
    } 

    return false; 
    } 

但它只返回true時一個值是完全一樣的。不是多維數組中的相應值,而不是相同值的百分比。

我想說這樣的話:如果「orchidtest」與多維數組中的[「title」]大於等於60%,那麼給這個值賦予百分比。

回答

1
<?php 
    $shop = array(
     array(
      'Title' => "rose", 
      'Price' => 1.25, 
      'Number' => 15 
     ), 
     array(
      'Title' => "daisy", 
      'Price' => 0.75, 
      'Number' => 25, 
     ), 
     array(
      'Title' => "orchid", 
      'Price' => 1.15, 
      'Number' => 7 
     ) 
    ); 

    function find_similar($compare, $array, $threshold = 0) 
    { 
     $return = array(); 
     $score; 
     foreach ($array as $k => $v) 
     { 
      similar_text($compare, $v['Title'], $score); 
      if ($score >= $threshold) 
      { 
       $return[] = array(
        'compared' => $compare, 
        'title' => $v['Title'], 
        'score' => number_format($score, 2) 
       ); 
      } 
     } 
     usort($return, function ($a, $b) 
     { 
      if((double)$a['score'] == (double)$b['score']) 
      { 
       return 0; 
      } 
      return ($a['score'] < $b['score']) ? 1 : -1; 
     }); 
     return $return; 
    } 

    $similar = find_similar('testorchid', $shop, 14); 
?> 

使你通過最相似的排序的陣列$similar,並且可以指定一個閾值來切斷無用值。

print_r($similar)輸出:

Array 
(
    [0] => Array 
     (
      [compared] => testorchid 
      [title] => orchid 
      [score] => 75.00 
     ) 

    [1] => Array 
     (
      [compared] => testorchid 
      [title] => rose 
      [score] => 14.29 
     ) 

) 

注意,菊花沒有得到回報,因爲它是相似跌破閾值。作爲參考,它的相似性是13.3333333r

+1

非常感謝你! – user1386906

+0

@ user1386906完全沒有問題,這是一個相當不錯的小挑戰:) – Dale

相關問題