存储这些短语的最快方法

时间:2016-11-27 16:31:52

标签: php algorithm search

构建一个简单的算法,根据各种输入(x,y,z),短语将被发送回用户。存储和搜索这些短语的最快方法是什么?

目前,我正在使用各种if语句。但我想知道我是否应该使用某种字典或哈希映射。

我在这里发布了一个代码示例。

谢谢!

  for ( $i=0 ; $i < count($age) ; $i++ ) {
    if ($age[$i] >= 95) { 
      $something = "You need a plant";
    } elseif ($age[$i] >= 85 && $age[$i] < 95) {
      $something = "You need a small rug and a plant";
    } elseif ($age[$i] >= 75 && $age[$i] < 85) {
      $something = "You need a rug";
    } elseif ($age[$i] >= 60 && $age[$i] < 75) {
      $something = "You need a coffee table";
    } elseif ($age[$i] >= 55 && $age[$i] < 60) {
      $something = "You need a small table";
    } elseif ($age[$i] >= 51 && $age[$i] < 55) {
      $something = "You need a table";
    } elseif ($age[$i] >= 42 && $age[$i] < 51) {
      $something = "You need a knife";
    } elseif ($age[$i] >= 35 && $age[$i] < 42) {
      $something = "You need a knife and a jar";
    } elseif ($age[$i] >= 22 && $age[$i] < 35) {
      $something = "You need a knife, bowl, jar and a small book";
    } elseif ($age[$i] >= 5 && $age[$i] < 22) {
      $something = "You need a knife, bowl, jar and a book";
    } else {
      $something = "Go back to sleep";
    }

    if ($somethingElse[$i] >= 30) {
      $also = " and we'll see you tomorrow!";
    } else {
      $also = ".";
    }

    $phrase[$i] = ''.$something.''.$also.'';
}

1 个答案:

答案 0 :(得分:1)

对于短语的第一部分,您可以使用年龄限制为键,文本为值的数组。对于第二部分,更多是是/否选择,您可以使用三元运算符。

foreach也可以更好地循环 $ age 数组:

$phrases = [
    95 => "You need a plant",
    85 => "You need a small rug and a plant",
    75 => "You need a rug",
    65 => "You need a coffee table",
    55 => "You need a small table",
    51 => "You need a table",
    42 => "You need a knife",
    35 => "You need a knife and a jar",
    22 => "You need a knife, bowl, jar and a small book",
    5  => "You need a knife, bowl, jar and a book",
];

foreach ($age as $i => $a) {
    foreach ($phrases as $limit => $something) {
        if ($a >= $limit) break;
    }
    $also = $somethingElse[$i] >= 30 ? " and we'll see you tomorrow!" : ".";
    $phrase[] = "$something$also";
}   

请注意,除非您已经有一个数组$phrase,否则您不需要指定索引 $ i ,因为[]只会将其追加到结束。所以最后你只需要{em> $ i $somethingElseforeach语法中仍然需要它的原因。