謀求最優的計算方法

來源:互聯網
上載者:User
尋求最優的計算方法
尋求最優的計算數組方法,實在搞不出來了
我有兩個數組分別是:
PHP code
$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
array(        'id'=>4,        'pos'=>4    ),


之上

------解決方案--------------------
PHP code
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'] < $arr2['id']) {                array_splice($arr1, $index - 1, 0, array($arr2));                break;            } else {                $insert = true;            }        } else if ($insert) {            break;        }        $index ++;    }    if ($insert) {        array_splice($arr1, $index - 1, 0, array($arr2));    }    return $arr1;}$arr1 = array_insert($arr1, $arr2);print_r($arr1);$arr2=array(    '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);?>
------解決方案--------------------
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);
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.