通过保持数组php [关闭]来合并两个数组而不更改键值
问题描述:
I have tree arrays in php as shown in the code
<?php
//old array
$oldArray = array(0 => 11, 1 => 18, 2 => 29, 3 => 35, 4 => 40);
// held values
$hold = array( 1 => 18, 3 => 35);
// new random generated array
$newValues = array( 0 => 27, 1 => 31, 2 => 38);
//I need keep keys (order, index) of $hold values
newArrayMergedPushed = array(0 => 27, 1 => 18, 2 => 31, 3 => 35, 4 => 38);
?>
I need keep order of $hold array in same order,index like in $oldArray. What function can I use in php so that the following output is obtained without changing key values?
答
If I'm guessing what you want to do correctly, it's probably better to operate directly on the array you want to change rather than creating a range first and then trying to mix them back in.
Hold only the indexes that you want to keep in a lookup table, then loop over the table and replace any key=>values that aren't held.
$oldArray = array(0 => 11, 1 => 18, 2 => 29, 3 => 35, 4 => 40);
$hold = array( 1 => true, 3 => true);
for( $i = 0; $i < count($oldArray); $i ++ ) {
if( !isset( $hold[$i] ) ) {
$oldArray[$i] = mt_rand(0,100); // or whatever you do to generate random numbers
}
}
That way you won't have to do any merging at all.