如何在两个指定键之间提取一系列元素?

时间:2017-03-30 06:49:21

标签: php arrays range slice offset

我有两个数组,第一个是:

Array (
  [0] => Mar
  [1] => Jun
)

,第二个是:

Array (
  [Jan] => January
  [Feb] => February
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
  [Jul] => July 
  [Aug] => August
  [Sep] => September
  [Oct] => October
  [Nov] => November
  [Dec] => December
)

我想从搜索数组中提取第一个指定月份的元素到第二个指定月份。

我的预期结果是:

Array (
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
)

2 个答案:

答案 0 :(得分:3)

请检查以下答案,可能会对您有所帮助:

$fullArray = [
    'Jan' => 'January',
    'Feb' => 'February',
    'Mar' => 'March',
    'Apr' => 'April',
    'May' => 'May',
    'Jun' => 'June',
    'Jul' => 'July',
    'Aug' => 'August',
    'Sep' => 'September',
    'Oct' => 'October',
    'Nov' => 'November',
    'Dec' => 'December',
];


$arrayToCompare = [
    'Mar', 'Jun'
];



$matchedArray = array();

$matchedFirst = false;
$matchedLast = false;

foreach ($fullArray as $key => $value) {
    if ($key == $arrayToCompare[0]) {
        $matchedFirst = true;
    }

    if ($key == $arrayToCompare[1]) {
        $matchedLast = true;
    }

    if ($matchedFirst == true) {
        $matchedArray[$key] = $value;
    }

    if ($matchedLast == true) {
        $matchedArray[$key] = $value;
        break;
    }

}

print_r($matchedArray);
die;

答案 1 :(得分:1)

一个简洁的解决方案可以更优雅地编写而无需使用条件循环。
我将提供一些干净的方法,每个方法只利用四个数组函数调用。

输入:

$months=[
    'Jan' => 'January',
    'Feb' => 'February',
    'Mar' => 'March',
    'Apr' => 'April',
    'May' => 'May',
    'Jun' => 'June',
    'Jul' => 'July',
    'Aug' => 'August',
    'Sep' => 'September',
    'Oct' => 'October',
    'Nov' => 'November',
    'Dec' => 'December'
];
$range=['Mar','Jun'];

方法#1 :(仅两行代码和四个函数)Demo

// create indexed array of keys in $month, retain only 2 selected months, get their indexes
$a=array_keys(array_intersect(array_keys($months),$range));
// slice the desired elements using offset and calculated length
var_export(array_slice($months,$a[0],$a[1]-$a[0]+1));

方法#2(只有四行代码和四个函数)Demo

$indexes=array_keys($months);  // generate an indexed array of abbreviated months
$start=array_search($range[0],$indexes);  // get the index of the starting month
$length=array_search($range[1],$indexes)-$start;  // subtract start from end month index
var_export(array_slice($months,$start,$length+1));  // extract the desired elements

输出:(使用任一方法)

array (
  'Mar' => 'March',
  'Apr' => 'April',
  'May' => 'May',
  'Jun' => 'June',
)