# 如何使用另一个数组操作数组？

Hi I have a problem to manipulate an array with another array like the sample seen below.

Sample scenario

Array one contains elements A, B, C, D, E ordering is strict

B's position is constant, it will not change in any manipulation

Array two contain X, Y

I need to merge array two with array one, merging result array will be:

Result array: X, B, Y, A, C D E

• A changed its position with X, because A's position isnot constant
• B's positions cannot changed, because B's position is constant
• C changed its position with Y, because C's position isnot constant
• A and C is appended after changes

Note: More than one element's positiob can be constant

What do you suggest for this kind of problem?

tHanks

Edit:

Thanks to @mkilmanas, I changed his code it works in the scenario described above

``````\$arrayOne   =   array(
0   =>  array('val' =>  'A','is_const'  =>  0),
1   =>  array('val' =>  'B','is_const'  =>  1),
2   =>  array('val' =>  'C','is_const'  =>  0),
3   =>  array('val' =>  'D','is_const'  =>  0),
4   =>  array('val' =>  'E','is_const'  =>  0)
);

\$arrayTwo   =   array(
0   =>  array('val' =>  'X','is_const'  =>  0),
1   =>  array('val' =>  'Y','is_const'  =>  0)
);

//Clone arrayOne
\$loose = \$arrayOne;

//Collect Fixed Elements
\$fixed = array();
foreach (\$arrayOne as \$idx=>\$val){
if (\$val['is_const'] == 1){
\$fixed[] = \$idx;
}
}

//Now remove fixed elements
//PHP doesn't reindex the array, so it is safe to use foreach here
foreach(\$fixed as \$idx) { unset(\$loose[\$idx]); }

//since they are numeric-indexed, they will be concatenated
//and the order is inverted, so that \$arrayOne is appended to the end of \$arrayTwo
\$combined = array_merge(\$arrayTwo, \$loose);

// And now we insert the fixed elements at their fixed positions
foreach(\$fixed as \$idx) {
array_splice(\$combined, \$idx, 0, array(\$arrayOne[\$idx]));
}
``````

Result of \$combined is X B Y A C D E which is correct

tHank you very much 2011/05/17 19:26
• php
• arrays
• 点赞
• 收藏
• 回答
私信