尋求最優的計算方法
尋求最優的計算數組方法,實在搞不出來了
我有兩個數組分別是:
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);