首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP & Array:计算两个键之间的距离

PHP & Array:计算两个键之间的距离
EN

Stack Overflow用户
提问于 2017-04-22 02:31:11
回答 2查看 546关注 0票数 0

具有类似于以下数组的数组:

代码语言:javascript
复制
$steps = array(0 => 'aaa', 1 => 'bbb', 2 => 'ccc', ......, 7 => 'hhh', 8 => 'iii', .....);

我如何计算从关键字7到达关键字2所需的步骤(关键字)?

EN

回答 2

Stack Overflow用户

发布于 2017-04-22 02:46:50

如果您的数字键从不缺少任何数字,则可以使用基本减法。

如果需要考虑可能缺少的数字,或者键不是数字,则可以组合使用array_keys()array_search()

代码语言:javascript
复制
$array = array(
    0 => 'aaa',
    1 => 'bbb',
    3 => 'ccc',
    'four' => 'ddd',
    900 => 'eee',
    13 => 'fff'
);

$from = 1;
$to = 900;

$keys = array_keys($array);

$from_index = array_search($from, $keys); // 1
$to_index = array_search($to, $keys); // 4

$steps = $to_index - $from_index;
// 3 steps: from 1-3, from 3-'four' and from 'four'-900
票数 2
EN

Stack Overflow用户

发布于 2017-04-25 01:30:04

我通过编写以下代码解决了这个问题:

代码语言:javascript
复制
$tot_step = 0;

$steps = array(
    0 => 'aaa',
    1 => 'bbb',
    2 => 'ccc',
    3 => 'ddd',
    4 => 'eee',
    5 => 'fff',
    6 => 'ggg',
    7 => 'hhh',
    8 => 'iii',
    9 => 'jjj',
    10 => 'aaa'
);

$from = "ddd";
$to = "bbb";

$from_index = array_search($from, $steps);
$to_index = array_search($to, $steps);

$last = $steps[(count($steps)-1)];

if ($from_index > 0) {

    if ($to == $last)
        $to_index = (count($steps)-1);

    $arr_l = count($steps);
    $mila = array();

    for ($ind = $from_index; $ind <= ($arr_l-1); $ind++) {

        if ($to == $last) {

            if ($steps[$ind] != $last)
                $mila[] = $steps[$ind];

        } else {

            $mila[] = $steps[$ind];

        }

        unset($steps[$ind]);

    }

    if (!empty($mila)) {

        for ($i = (count($mila)-1); $i >= 0; $i--)
            array_unshift($steps, $mila[$i]);

    }

    $to_new = array_search($to, $steps);

    foreach ($steps as $key => $value) {

        if ($key == $to_new)
            break;
        else
            $tot_step++;

    }


} elseif ($from_index == 0) {

    if ($to_index == $from_index) {

        $tot_step = (count($steps)-1);

    } else {

        foreach ($steps as $key => $value) {

            if ($key == $to_index)
                break;
            else
                $tot_step++;

        }

    }

}

echo $tot_step;

我希望它能对某些人有用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43549712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档