PHP - Create a dynamic array based on cycles

0

I find a big problem, I want to add an array within an array, but I can not find a solution, my code is this:

$arrayDetalle = Array();
for($i = 0; $i < $this->contArticulos; $i++){
    $arrayDetalle = array(
        "Nombre"        => $this->nombreVFI[$i],
        "Cantidad"      => $this->cantidadVFI[$i],
        "Subtotal"      => $this->costo_subtotalVFI[$i],
        "Total"         => $this->costo_subtotalVFI[$i] + $this->costo_impuestoVFI[$i],
        "Codigo"        => $this->codigoVFI[$i],
        "Impuestos"     => array(
            "Impuesto"      => $this->impuestoVFI[$i],
            "Porcentaje"    => $this->valor_impuestoVFI[$i],
            "TotalImp"      => $this->costo_impuestoVFI[$i]
        )
    );
}

And then I need to convert that array into a json and display it on the screen, but when I print it, nothing appears on the screen:

$json = json_enconde($arrayDetalle);
echo $json;
    
asked by David Espinal 06.10.2017 в 23:57
source

3 answers

2

You are overwriting the variable, it would look like this:

$arrayDetalle = Array();
for($i = 0; $i < $this->contArticulos; $i++){
    $arrayDetalle[] = array(  #Aquí está la respuesta, usa [] luego del nombre del array.
        "Nombre"        => $this->nombreVFI[$i],
        "Cantidad"      => $this->cantidadVFI[$i],
        "Subtotal"      => $this->costo_subtotalVFI[$i],
        "Total"         => $this->costo_subtotalVFI[$i] + $this->costo_impuestoVFI[$i],
        "Codigo"        => $this->codigoVFI[$i],
        "Impuestos"     => array(
            "Impuesto"      => $this->impuestoVFI[$i],
            "Porcentaje"    => $this->valor_impuestoVFI[$i],
            "TotalImp"      => $this->costo_impuestoVFI[$i]
        )
    );
}

With this you indicate that another element will be added to $arrayDetalle[] = ..

    
answered by 07.10.2017 / 00:05
source
1

The name of the function is misspelled:

$json = json_enconde($arrayDetalle);

It should be json_encode !

    
answered by 07.10.2017 в 01:00
0

I think this will work ...

$arrayDetalle   = array();
$arrayImpuestos = array();
for ( $i = 0; $i < $this->contArticulos; $i++ ) {

    $arrayImpuestos[ "Impuesto" ]   = $this->impuestoVFI[ $i ];
    $arrayImpuestos[ "Porcentaje" ] = $this->valor_impuestoVFI[ $i ];
    $arrayImpuestos[ "TotalImp" ]   = $this->costo_impuestoVFI[ $i ];

    $arrayDetalle[ "Nombre" ]    = $this->nombreVFI[ $i ];
    $arrayDetalle[ "Cantidad" ]  = $this->cantidadVFI[ $i ];
    $arrayDetalle[ "Subtotal" ]  = $this->costo_subtotalVFI[ $i ];
    $arrayDetalle[ "Total" ]     = ($this->costo_subtotalVFI[ $i ] + $this->costo_impuestoVFI[ $i ]);
    $arrayDetalle[ "Codigo" ]    = $this->codigoVFI[ $i ];
    $arrayDetalle[ "Impuestos" ] = $arrayImpuestos;
}
    
answered by 07.10.2017 в 00:09