RustyBadRobot
RustyBadRobot

Reputation: 566

PHP how do I include an unknown quantity of arrays within my variable

I am trying to recreate the below but within a PHP for loop. This is the original code that I need to replicate.

$values[ 'value' ] = array(
'form' => '1647',
  'row_ids' => array( 0, 1, 2 ),
  0 => array( 0 => '', $first_field => 'Row 1 value', $second_field => '1' ),
  1 => array( 0 => '', $first_field => 'Row 2 value', $second_field => '2' ),
  2 => array( 0 => '', $first_field => 'Row 3 value', $second_field => '3' ),
);
return $values;
}

I need to create a dynamic version of this, I thought the below code would work but it seems this is creating a parent array I don't need and I am stuck with what to do next.

$i = 0;
$count = "0";
$row_values = array();

for ($x = 0; $x < $row_num; $x++) {
  if($x != 0) {
    $i++;
    $count .= ", " . $x;
  }
  $row_values[$i][0] = '';
  $row_values[$i][$first_field] = 'Row 1 value';
  $row_values[$i][$second_field] = "$i";
}

$values[ 'value' ] = array(
  'form' => '1647',
  'row_ids' => array( $count ),
  $row_values
);

So to clarify my code is creating:

Array ( [0] => Array ( [0] => [22] => Row 1 value [23] => 0 ) [1] => Array ( [0] => [22] => Row 1 value [23] => 1 ) );

And I need:

[0]=> array(3) { [0]=> string(0) "" [22]=> string(11) "Row 1 value" [23]=> string(1) "1" }

[1]=> array(3) { [0]=> string(0) "" [22]=> string(11) "Row 2 value" [23]=> string(1) "2" }

This needs to work for any amount of rows i.e. 2 as per the example or 5 or x.

Upvotes: 1

Views: 50

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Just define your array and then add to it based on the increment:

$values['value'] = array( 'form' => '1647' );

for($x = 0; $x < $row_num; $x++) {
    $values['value']['row_ids'][$x] = $x;
    $values['value'][$x] = array( 0 => '',
                                  $first_field => 'Row ' . ($x + 1) . ' value',
                                  $second_field => ($x + 1) );
}

Upvotes: 1

Tesla
Tesla

Reputation: 189

I didn't understand clearly what you are trying to achieve but there is a simplified version.

<?php
$arr = [];
$arr_n = 3;

for ($i = 1; $i < $arr_n + 1; ++$i) {
    $arr['value'][] = ["Row $i value" => $i];
}

print_r($arr);

preview

Array
(
    [value] => Array
        (
            [0] => Array
                (
                    [Row 1 value] => 1
                )

            [1] => Array
                (
                    [Row 2 value] => 2
                )

            [2] => Array
                (
                    [Row 3 value] => 3
                )

        )

)

Upvotes: 0

Related Questions