PHP&数组:计算两个键之间的距离

时间:2017-04-21 18:31:11

标签: php arrays pointers count position

有一个类似于下面的数组:

$steps = array(0 => 'aaa', 1 => 'bbb', 2 => 'ccc', ......, 7 => 'hhh', 8 => 'iii', .....);

如何根据序列7来计算从密钥7到达密钥2所需的步数(密钥)?

2 个答案:

答案 0 :(得分:2)

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

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

$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

答案 1 :(得分:0)

I solved this problem by writing this code:

$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;

I hope it will be useful to someone