How to insert the elements of the X array into an index of the Y array?

Asked

Viewed 161 times

2

I own the array y where in your index 0 holds the values App and Views

array (size=1)
  0 => 
    array (size=2)
      0 => string 'App' (length=3)
      1 => string 'Views' (length=5)

In the x I have a array with N values

array (size=1)
      0 => 'a'
      1 => 'b'
      ...

And I want to add them to the first index of array x, when using array_merge do not get the expected result:

array (size=1)
      0 => 
        array (size=2)
          0 => string 'App' (length=3)
          1 => string 'Views' (length=5)
      1 => 'a'
      2 => 'b'

When it should be:

array (size=1)
      0 => 
        array (size=2)
          0 => string 'App' (length=3)
          1 => string 'Views' (length=5)
          2 => string 'a'
...

Example:

$ranking[] = ['App', 'Views'];

$options[] = ['A', 'B'];

$merge = array_merge($ranking, $options);
$merge2 = array_merge($ranking[0], $options);

var_dump($merge);
var_dump($merge2);

Example in ideone

  • Put the ideone code in the question :)

  • Would that be so? https://ideone.com/IWahLp

  • @rray Ops! Edited!

  • Apparently yes, @Rafaelwithoeft

2 answers

5


You must select the appropriate array (position 0 of the y array) to merge:

$y[0] = array_merge($y[0],$x);

3

With PHP5.6 you can simplify this assignment by combining array_push() and the operator eclipse(...), it unpacks each element of the array as an argument to push_array(), in practice the generated instruction would be something like array_push($ranking[0], 'A', 'B', 'C')

Example - ideone

<?php
   $ranking[] = ['App', 'Views'];
   $options[] = ['A', 'B'];
   array_push($ranking[0], ...$options[0]);

   echo "<pre>";
   print_r($ranking);

Exit:

Array
(
    [0] => Array
        (
            [0] => App
            [1] => Views
            [2] => A
            [3] => B
        )

)

Related:

What is the name of the ... operator used in PHP 5.6?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.