Home >Backend Development >PHP Tutorial >流程算法解决方案

流程算法解决方案

WBOY
WBOYOriginal
2016-06-13 12:01:26972browse

流程算法
简单说明
我定义咯一个数组,
数组的key表示当前步的ID,下一步的ID对应的value...
我要生成一个这个新的数组
例子:
array(1 => int 7
  7 => int 11
  8 => int 7
  9 => int 8
  10 => int 11
  11 => int 12
  12 => NULL
)
结果就是
array(
1=>7
7=>11
11=>12
12=>NULL
)
当前知道开头位为1.

求算法...
------解决方案--------------------

本帖最后由 xuzuning 于 2014-07-04 21:16:48 编辑
$a = array(<br />  1 => 7,<br />  7 => 11,<br />  8 => 7,<br />  9 => 8,<br />  10 => 11,<br />  11 => 12,<br />  12 => NULL,<br />);<br />$i = 1;<br />while(isset($a[$i])) {<br />  $r[$i] = $a[$i]; <br />  $i = $a[$i];<br />}<br />$r[$i] = $a[$i]; <br />var_export($r);<br />
array (
  1 => 7,
  7 => 11,
  11 => 12,
  12 => NULL,
)

------解决方案--------------------
<br />$map = array(<br />    1 => 7,<br />    7 => 11,<br />    8 => 7,<br />    9 => 8,<br />    10 => 11,<br />    11 => 12,<br />    12 => NULL<br />);<br /><br />function getroad($map){<br />    $key = 1;<br />    $result = array();<br />    while($key!=NULL){<br />        $result[$key] = $map[$key];<br />        $key = $map[$key];<br />    }<br />    return $result;<br />}<br /><br />$result = getroad($map);<br /><br />var_export($result);<br />



array (
  1 => 7,
  7 => 11,
  11 => 12,
  12 => NULL,
)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn