[英]How to search for a value in a sub array and get to know the key index of that sub array
我有一个这种结构的数组:
$months = array(
MM => array(
'start' => DD,
'end' => DD,
'type' => (string),
'amount'=> (float),
),
);
MM是一个月(01-12,字符串),DD是一个月中的一天(01-31,字符串)。 并非所有月份都在阵列中。 对于每个月,存在可变数量的子阵列,每个子阵列具有唯一的天数。 例如,一个月有三个具有三个天数范围的子阵列,但这些范围中使用的天数永远不会重叠或重复,每个DD值都是唯一的。 唯一的例外是在某些范围内“开始”和“结束”可能重合(同一个DD日),但每个月永远不会有两个相同的“开始”日或两个相同的“结束日”。
我需要在每个月内循环几个月和几天时使用此数组。 在循环每月的每一天时,我需要检查特定日期是否在“开始”或“结束”中匹配。 如果匹配为真,我还需要检索相邻的值。
在这样做时,我遇到了一个问题:如何知道子阵列的关键索引? 例如,我如何知道匹配是否开启
$months['09'][3]['start'] == $current_day_in_loop;
更确切地说:
$months['09'][6]['start'] == $current_day_in_loop;
还是另一把钥匙?
由于我不知道每个月有多少范围,因此索引键是可变的,或者可能根本没有。 如何找到匹配值是否在键[3]
或[6]
? 一旦我知道了密钥,我就可以用它来查找同一子阵列中的相邻值。
您可以执行过滤器以确定哪些天匹配:
$matches = array_filter($months['09'], function($item) use ($current_day_in_loop) {
return $item['start'] == $current_day_in_loop;
});
// if $matches is empty, there were no matches, etc.
foreach ($matches as $index => $item) {
// $months['09'][$index] is the item as well
}
请尝试使用以下示例获取密钥:
//loop start
if (($key = array_search($searchedVal, $dataArr)) !== false) {
echo $key;
}
// loop end
如果匹配为真,我还需要检索相邻的值。 在这样做时,我遇到了一个问题:如何知道子阵列的关键索引? 例如,我如何知道匹配是否开启
如果我理解正确,你遇到的主要问题是你想要检索匹配的下一个和前一个元素,但不知道如何,因为你不知道键是什么。
您可以通过next
遍历数组来实现此目的
$months = array(
'01' => array(
'start' => '1',
'end' => '31',
'type' => 'hello',
'amount'=> 2.3,
),
'02' => array(
'start' => '2',
'end' => '31',
'type' => 'best',
'amount'=> 2.5,
),
'03' => array(
'start' => '3',
'end' => '31',
'type' => 'test',
'amount'=> 2.4,
),
);
$matches = array();
$prev = null;
$prev_key = null;
$key = key($months);
$month = reset($months);
while($month) {
$next = next($months);
$next_key = key($months);
foreach(range(1,31) as $current_day_in_loop) {
//if end or start match grab the current, previous and next values
if($month['start'] == $current_day_in_loop
|| $month['end'] == $current_day_in_loop) {
$matches[$key] = $month;
if($prev)
$matches[$prev_key] = $prev;
if($next)
$matches[$next_key] = $next;
}
}
$prev = $month;
$prev_key = $key;
$month = $next;
$key = $next_key;
}
print_r($matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.