Home  >  Article  >  Backend Development  >  谋求最优的计算方法

谋求最优的计算方法

WBOY
WBOYOriginal
2016-06-13 13:06:16893browse

寻求最优的计算方法
寻求最优的计算数组方法,实在搞不出来了
我有两个数组分别是:

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
$arr1=array(
    array(
        'id'=>1,
        'pos'=>1
    ),
    array(
        'id'=>2,
        'pos'=>2
    ),
    array(
        'id'=>3,
        'pos'=>3
    ),
    array(
        'id'=>4,
        'pos'=>4
    ),
    array(
        'id'=>5,
        'pos'=>5
    ),
    array(
        'id'=>6,
        'pos'=>6
    ),
)

$arr2=array(
    'id'=>7,
    'pos'=>4
)



首先查找$arr2的pos在$arr1中的所有数组的pos中的顺序位置,如果顺序位置一致则按照id倒序获取位置

如上面的代码则应该获取的结果为:$arr2位于$arr1的
PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
array(
        'id'=>4,
        'pos'=>4
    ),



之上

------解决方案--------------------
PHP code


<?php $arr1=array(
    array(
        'id'=>1,
        'pos'=>1
    ),
    array(
        'id'=>2,
        'pos'=>2
    ),
    array(
        'id'=>3,
        'pos'=>3
    ),
    array(
        'id'=>4,
        'pos'=>4
    ),
    array(
        'id'=>5,
        'pos'=>5
    ),
    array(
        'id'=>6,
        'pos'=>6
    ),
);

$arr2=array(
    'id'=>7,
    'pos'=>4
);

function array_insert($arr1, $arr2)
{
    $index = 1;
    $insert = false;
    foreach($arr1 as $v)
    {
        if ($v['pos'] == $arr2['pos']) {
            if ($v['id'] 3,
    'pos'=>4
);
$arr1 = array_insert($arr1, $arr2);
print_r($arr1);

$arr2=array(
    'id'=>5,
    'pos'=>6
);
$arr1 = array_insert($arr1, $arr2);
print_r($arr1);
?>
<br><font color="#e78608">------解决方案--------------------</font><br>
当
PHP code
$arr1=array(
    array(
        'id'=>1,
        'pos'=>1
    ),
    array(
        'id'=>2,
        'pos'=>2
    ),
    array(
        'id'=>3,
        'pos'=>3
    ),
    array(
        'id'=>4,
        'pos'=>5
    ),
    array(
        'id'=>5,
        'pos'=>5
    ),
    array(
        'id'=>6,
        'pos'=>6
    ),
);

$arr2=array(
    'id'=>7,
    'pos'=>4
); <div class="clear">
                 
              
              
        
            </div>
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