How to add more positions in zero to an array [duplicated]

0

friends I have this result

array(3) {
  [0]=>
  array(1) {
    ["dato"]=>
    string(7) "3522.40"
  }
  [1]=>
  array(1) {
    ["dato"]=>
    string(7) "6748.20"
  }
  [2]=>
  array(1) {
    ["dato"]=>
    string(7) "7000.00"
  }

Inserting new data would be something like this:

[3]=>
array(1) {
   ["dato"]=>string(1) "0"
}

I need to be able to add more fields to the vector, after position [2].

    
asked by Jassan 24.10.2017 в 23:22
source

2 answers

1

One way would be to get the total number of records that the array has with the function count and then assign the new value in that position.

  

Since I do not know the name of the variable that the array generates, I will use $ a as a reference.

$posicion = count($a);  //Count devuelve la cantidad de registros que tiene el arreglo.


$a[$posicion]['dato'] = "0";  //Asigno en esa posición el valor que deseo almacenar.

var_dump($a);
  

The var_dump ($ a) prints the following:

    array(3) {
  [0]=>
  array(1) {
    ["dato"]=>
    string(7) "3522.40"
  }
  [1]=>
  array(1) {
    ["dato"]=>
    string(7) "6748.20"
  }
  [2]=>
  array(1) {
    ["dato"]=>
    string(7) "7000.00"
  }
  [3]=>
  array(1) {
    ["dato"]=>
    string(1) "0"
  }
    
answered by 25.10.2017 / 00:06
source
0

If your array contains numeric indexes (that is, it is not an associative array) you can simply do this:

<?php
$a[] = ['dato' => 'loquesea']; 

There's also the array_push function, which does exactly the same as the code above:

<?php
array_push($a, ['dato' => 'loquesea']);
    
answered by 25.10.2017 в 10:03