skip to Main Content

used php for a while but cannot get what is going on here! I’ve tried array_merge() and array_push() on an array to be able to add arrays to an array of existing arrays.

For example, to be able to add x and y into the same array using a loop:

$x = [x, y, z];
$y = [a, b, c];

$goal = [[x, y, z], [a,b,c]];

Feel like I am so dinged up on this problem I am missing something really obvious!
I’ve tried all of the following but have had nothing work.

$intermediate = array([x,y,z];;
$goal = array($goal, $intermediate)

$goal[$i] = $intermediate;

$goal[$i][$j] = $raw[i][j]; // lets say raw is where elements come from

From what I have seen this is an indexed array that is multidimensional but I am completely stuck as I have been working it for hours! Any help appreciated!

[EDIT] Essentially I am trying to push into Google sheets and it accepts input of the form [[$val1], [$val2]] for an insertion for two columns and of the form [[$val1, $val2]] for an insertion into a row.

I have a 2d array, where each array will be a separate row but it doesn’t seem to be working. I am updating $goal to $goal = [$goal, $intermediates] but it doesn’t seem to work – it only keeps the first line.

My goal is to push content of the form [[$val1,$val2],[$val3,$val4]] but it only inserts the [$val1,$val2] part.

$goal = [];
for ($i = 0; $i < count( $info) ; $i++){
  $value1 = $info[$i][0]; // fname
  $value2 = $info[$i][1]; // lname
  $value3 = $info[$i][2]; // age

  $person =[$value1, $value2, $value3];


  $goal = [$goal, $person];
 
}

I have also tried with the array() version rather than the square brackets.

2

Answers


  1. You could either, store the array into variables and create a new array from both :

    $array1 = ['a', 'b', 'c'];
    $array2 = ['x', 'y', 'z'];
    
    $outputArray = [$array1, $array2];
    

    Or build it using the [] operator.

    $outputArray = [];
    $outputArray[] = ['a', 'b', 'c'];
    $outputArray[] = ['x', 'y', 'z'];
    

    It seams to be working fine both ways

    EDIT With your new addition, you were very close. What you need is to use the [] operator on the $goal array. This operator adds another element to an array. In our case, we want to add $person, since it’s the newly created row.

    $goal = [];
    for ($i = 0; $i < count($info) ; $i++){
        
      $value1 = $info[$i][0]; // fname
      $value2 = $info[$i][1]; // lname
      $value3 = $info[$i][2]; // age
    
      $person =[$value1, $value2, $value3];
    
    
      $goal[] = $person;
     
    }
    

    You can use this playground to checkout a working example.

    Login or Signup to reply.
  2. Just use array_push function:

    <?php
    $x = ['x', 'y', 'z'];
    $y = ['a', 'b', 'c'];
    
    $goal = [];
    
    array_push($goal, $x, $y);
    
    print_r($goal);
    

    Here you can play this PHP code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search