嗨我有一个问题是用另一个数组操作数组,如下面的示例所示。
示例方案
数组一包含元素 A,B,C,D,E 排序严格
B的位置是恒定的,在任何操作中都不会改变
数组2包含 X,Y
我需要将数组二合并到数组一,合并结果数组将是:
结果数组: X,B,Y,A,C D E
注意: 不止一个元素的positiob可以是常数
你对这类问题有什么建议?
感谢
编辑:
感谢@mkilmanas,我在上述场景中改变了他的代码
$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]));
}
$ combined的结果是 X B Y A C D E 这是正确的
非常感谢你
答案 0 :(得分:1)
我会使用array_merge()
和array_splice()
的组合。让我们假设$fixed
包含一组固定元素的键(来自$arrayOne
)。
$loose = $arrayOne; // Copy initial array
// 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, $arrayOne);
// And now we insert the fixed elements at their fixed positions
foreach($fixed as $idx) {
array_splice($combined, $idx, 0, array($arrayOne[$idx]));
}
// voila - $combined should now have the desired order
答案 1 :(得分:0)
您可以使用与第一个数组相同长度的第二个布尔值数组。布尔数组中的每个元素都会告诉第一个数组中的相应元素是否可移动。然后,你可以适当地改变一切。
答案 2 :(得分:0)
您可能希望首先构建一个包含每个级别的插槽/排名的多维数组,如:
$multi[10][] = $x;
$multi[10][] = $b;
$multi[20][] = $y;
$multi[20][] = $a;
完成后,您可以在保留订单的同时展平阵列。