基于多维数组中的匹配值返回值

时间:2012-08-17 06:22:10

标签: php multidimensional-array

我有一个多维数组,包括(a)描述,(b)最小年数和(c)最大年数:

$years_array = array( 
 array("Any", 0, 255),
 array("New", 0, 1),
 array("5 - 10yrs", 5, 10),
 array("10 - 20yrs", 10, 20)
);

同时给出最小$min和最长$max年数,如何匹配它以在数组中提供描述$description

示例:

$min = 5, $max = 10 => $description = "5 - 10yrs";

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

function getDescription($min,$max) 
{
  // source
  $years_array = array( 
    array("Any", 0, 255),
    array("New", 0, 1),
    array("5 - 10yrs", 5, 10),
    array("10 - 20yrs", 10, 20)
  );
  foreach ($years_array as $yearRecord) {
    if ($min == $yearRecord[1] && $max == $yearRecord[2])) {
      return $yearRecord[0];
    }
  }
  return false;
}

getDescription(0, 255); // == "Any"

答案 1 :(得分:1)

function searchArray($min, $max, $years_array)
{
  foreach($years_array as $years)
  {
    if($years[1] == $min && $years[2] == $max) return $years[0];
  }
}

答案 2 :(得分:1)

快速,肮脏,只是为了展示一种可能性......

<?php
$years_array = array( 
 array("Any", 0, 255),
 array("New", 0, 1),
 array("5 - 10yrs", 5, 10),
 array("10 - 20yrs", 10, 20)
);

function getYearDescription(&$years, $min, $max) {
 foreach($years as $year) {
  if($year[1] == $min && $year[2] == $max) {
    return $year[0];
  }
 }

 return "n/a";
}

echo(getYearDescription($years_array, 5, 10));
?>

我想你需要完全匹配