Looking for the optimal calculation method to find the optimal calculation array method, we can't figure out that I have two arrays: PHPcode $ arr1array (array (id & gt; 1, pos & gt; 1), array (id & gt; 2, pos & gt; 2), find the optimal calculation method
Looking for the optimal array calculation method cannot be achieved.
I have two arrays:
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)
First, find the order position of the pos of $ arr2 in the pos of all arrays of $ arr1. if the order position is the same, obtain the position by id in reverse order.
The result of the above code is: $ arr2 is located in $ arr1
PHP code
array( 'id'=>4, 'pos'=>4 ),
Above
------ Solution --------------------
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;} el Se {$ 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);?>
------ Solution --------------------
When
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);