Undefined offset php when traversing PHP Array

0

I'm trying to go through the following array :

([items] => Array(
           [1] => Array
               (
                [productCode] => DIEZ MIL 10,000 NEGRO 34
                [cantidad] => 1
                [precio] => 1
               )
           [2] => Array(
                [productCode] => DIEZ MIL 10,000 NEGRO 35
                [cantidad] => 1
                [precio] => 1
               )
           [4] => Array(
                [productCode] => DIEZ MIL 10,000 CAFE 39
                [cantidad] => 1
                [precio] => 1
              )
           )

but I get the error

  

Undefined offset

    
asked by Luis Amilcar 01.04.2017 в 07:38
source

1 answer

3

The Undefined offset occurs when you try to access an element of the array that does not exist.

To walk UN array the simplest would be a foreach , If the data you want to obtain requires this path to reach them. (asexposedexample)

Array [ Array { Array (Valores) : Array(Valores) : Array(Valores) } ]

That is, a foreach for each Array Internal (three in total)

$array = array('items' =>array(
array(
    'productCode' => 'DIEZ MIL 10,000 NEGRO 34',
    'cantidad' => 1,
    'precio' => 1
),
array(
    'productCode' => 'DIEZ MIL 10,000 NEGRO 35',
    'cantidad' => 2,
    'precio' => 2
),
array(
    'productCode' => 'DIEZ MIL 10,000 CAFE 39',
    'cantidad' => 3,
    'precio' => 3
) 
));   

foreach ($array as $key => $value) { /* Array Items */
    foreach($value as $key2 => $value2){ /* Siguiente  Array */
        foreach($value2 as $key3=> $value3)/* Siguiente  Array (3) */
            echo $key3 .  "-- " .$value3 . "<br>";
    }
 }

/*  Otra forma de acceder */

foreach($array as $key => $value){
  for ($i=0; $i < count($value); $i++) { 
    echo ("Producto : " . $value[$i]['productCode'] . " Cantidad : " . $value[$i]['cantidad'] . " Precio : " .$value[$i]['precio']);
    echo "<br>" ;
 }
}
    
answered by 01.04.2017 / 08:21
source