Sometip
Sometip

Reputation: 352

Merge two arrays with random key indexes and then sort by the key index

Say you have these two arrays:

$a = array( 
  1 => 'This should be position #1 in merged array' 
);

$b = array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);

How can you end up with a new array that looks like this:

$merged_a_b = array( 
  0 => 'This should be position #0 in merged array',
  1 => 'This should be position #1 in merged array',
  2 => 'This should be position #2 in merged array',
);

I tried array_merge( $a, $b ), but it changes the key indexes and results in this:

array (size=3)
  0 => string 'This should be position #0 in merged array' (length=42)
  1 => string 'This should be position #2 in merged array' (length=42)
  2 => string 'This should be position #1 in merged array' (length=42)

As you can see, the values are in the wrong order.

Upvotes: 0

Views: 134

Answers (3)

Rahul K
Rahul K

Reputation: 413

You can use same variable using += assignment operator to merge multiple arrays in a single variable as below. after you can use ksort function to reorder array keys and its values.

$array = array( 
  1 => 'This should be position #1 in merged array' 
);
$array += array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);
ksort($array);

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

If you need to preserve the keys, you can use array_replace():

$a = array( 
    1 => 'This should be position #1 in merged array' 
);
$b = array( 
    0 => 'This should be position #0 in merged array',
    2 => 'This should be position #2 in merged array',
);
array_replace($a, $b);

And then use ksort() to sort according to keys:

ksort($a);

Upvotes: 3

G1.3
G1.3

Reputation: 1879

You can also use the + operator then the ksort function:

$a = array( 
  1 => 'This should be position #1 in merged array' 
);

$b = array( 
  0 => 'This should be position #0 in merged array',
  2 => 'This should be position #2 in merged array',
);

$merged = $a + $b;
ksort($merged);

Upvotes: 1

Related Questions