获取多维数组中最接近的较小数组键



我有一个数组$curvepoint,其结构如下:

Array
(
    [0] => Array
        (
            [ID] => 57587
            [Pos0] => 1
        )
    [1] => Array
        (
            [ID] => 57588
            [Pos0] => 2
        )
    [2] => Array
        (
            [ID] => 57589
            [Pos0] => 22
        )
    [3] => Array
        (
            [ID] => 57590
            [Pos0] => 39
        )
)

现在,我想获得与值[Pos0]和给定数字最接近的较小数组键。

示例:

如果我有变量$number = 20,循环应该返回1,因为20的最接近的较小[Pos0]值将是存储在array key 1中的[Pos0] => 2

我很不确定如何得到结果。我曾尝试在foreach循环中使用array_slice和array_incross的组合。

原始尝试:

$number = 20 
foreach ($curvepoint as $test) {
    $two_nearest = array_slice(array_intersect(array_keys($test['Pos0']),range(0,$number)), -2);
    $less_near = $test['Pos0'][$two_nearest[0]];
    echo $less_near;
}

编辑代码:

$value = 10;
function findClosestLowerPosition(array $curvepoint , int $value): ?int
{
    $lowerPositions = array_filter(
        array_column($curvepoint , 'Pos0'),
        function ($a) use ($value) {
            return $a < $value;
        }
    );
    if (empty($lowerPositions)) {
        return null;
    }
}
print_r($lowerPositions);

建议的解决方案:

/**
 * Searches for the index of an element that has the closest of all
 * the lower values than the specified one.
 *
 * @return int|null Numeric position of the closest lower element if found,
 * NULL otherwise
 */
function findClosestLowerPosition(array $curvepoints, int $value): ?int
{
    $lowerPositions = array_filter(
        array_column($curvepoints, 'Pos0'),
        function ($a) use ($value) {
            return $a < $value;
        }
    );
    if (empty($lowerPositions)) {
        return null;
    }
    rsort($lowerPositions);
    $closestPosition = $lowerPositions[0];
    foreach ($curvepoints as $key => $curvepoint) {
        if ($curvepoint['Pos0'] === $closestPosition) {
            return $key;
        }
    }
}

工作原理:

  • 第一步获取所有较低位置的值。这是通过首先从CCD_ 10提取每个CCD_。该函数的结果是一个简单的数字数组,然后将其作为参数传递给array_filter,后者只过滤低于指定值的值
  • 之后,我们检查是否有任何更低的值——如果没有找到,我们的过滤数组将为空。在这种情况下,我们返回null来表示不存在这样的值
  • 一旦我们有了较低的值,我们就按相反的顺序(从大到低(对它们进行排序,以便将最接近的值放在数组的第一个位置,然后我们通过访问第一个索引来获得它(对于PHP自动生成的数组,它总是0(
  • 最终,我们迭代原始数组,以定位其值与最接近的值匹配的元素。一旦找到匹配项,我们就会返回该元素的键

注意,整个算法假设Pos0不存在重复值。如果元素可以具有相同的位置值,则需要确定如何打破关系的规则。

最新更新