Majid Fouladpour
Majid Fouladpour

Reputation: 30252

Insert an array at position x of an array of arrays

We have an array of ranges in $r:

$r = array( array(3,5), array(36,54) );

We want to add a new range to our ranges:

$n = array(11, 19);

We also want $r to be sorted, so the new range should be inserted at position 1. If we use array_splice the result would be having 11 and 19 added as two new elements:

array_splice($r, 1, 0, $n);
// output: array( array(3,5), 11, 19, array(36,54) )

How can we get the desired result as shown below?

// output: array( array(3,5), array(11,19), array(36,54) )

Upvotes: 0

Views: 65

Answers (3)

Bob Nocraz
Bob Nocraz

Reputation: 446

If you are simply wanting them to be in order of the first value in the range, then you could do the following.

$r = array( array(3,5), array(36,54));
$r[] = array(11,19);
print_r($r);
sort($r);
print_r($r);

results:

Not sorted:

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 5
        )

    [1] => Array
        (
            [0] => 36
            [1] => 54
        )

    [2] => Array
        (
            [0] => 11
            [1] => 19
        )

)

Sorted:

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 5
        )

    [1] => Array
        (
            [0] => 11
            [1] => 19
        )

    [2] => Array
        (
            [0] => 36
            [1] => 54
        )

)

view this answer to another question that explains why sort() works on multidimensional arrays

Upvotes: 0

helmbert
helmbert

Reputation: 37984

This may be easier that you think. Reading array_splice's documentation, you see that the $replacement parameter is an array and should contain all elements that should be inserted into the array.

So consider the following code:

array_splice($r, 1, 0, array(11, 19));

This does not insert array(11, 19) as one element into the array, but each 11 and 19 as two elements.

What you probably want to do is this:

array_splice($r, 1, 0, array(array(11, 19)));

Or, in your concrete example:

array_splice($r, 1, 0, array($n));

Alternatively, you could simply append and then completely re-sort the array (which might be not as efficient, but a bit easier for small data sets):

$r[] = $n;
usort($r, function($a, $b) { return $a[0] - $b[0]; });

Upvotes: 2

potashin
potashin

Reputation: 44581

You can wrap array with new range in another array:

array_splice($r, 1, 0, array($n));

Output:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(5)
  }
  [1]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(19)
  }
  [2]=>
  array(2) {
    [0]=>
    int(36)
    [1]=>
    int(54)
}

Example

Upvotes: 3

Related Questions