Accessing data from an array

Asked

Viewed 73 times

1

I’m having a problem up to half "beast" here.

I have the following array

array(1) {
  [0]=>
  array(7) {
    ["id"]=>
    string(1) "6"
    ["produto"]=>
    string(1) "7"
    ["peso"]=>
    string(1) "1"
    ["comprimento"]=>
    string(2) "16"
    ["largura"]=>
    string(2) "15"
    ["altura"]=>
    string(1) "5"
    ["diametro"]=>
    string(1) "0"
  }
}

But every time I try to access something of it, php complains undefined index

I’m accessing it as follows

$vetor['produto']
$vetor['peso']

What would be the right way to access it?

1 answer

3


Has the Intel zero before id and the others, the right is $vetor[0]['produto']. One way to see organized array or object structure is to use this code

echo '<pre>';
print_r($arr);

Thus it is explicit which element contains which.

The structure of yours is this:

<?php 

$arr = array(
        0 => array('id' => 6, 'produto' => 7, 'peso' => 1, 'comprimento' => 16, 'largura' => 15, 'altura' => 5, 'diametro' => 0)
);

echo '<pre>';
print_r($arr);

And satida with the <pre> evidence which elements are inside the zero Indice.

Array
(
    [0] => Array
        (
            [id] => 6
            [produto] => 7
            [peso] => 1
            [comprimento] => 16
            [largura] => 15
            [altura] => 5
            [diametro] => 0
        )

)

If you want to select Dice Zero you can use array_shift() or array_pop()

echo '<pre>';
$arr = array_shift($arr);
print_r($arr);

Satida:

Array
(
    [id] => 6
    [produto] => 7
    [peso] => 1
    [comprimento] => 16
    [largura] => 15
    [altura] => 5
    [diametro] => 0
)
  • I can barely see your movements, I was with the ideone so ready here kkkk

  • @Diegofelipe hahaha, I even found it funny to see this question unanswered for 40 minutes rs

  • I was, but before I took a beating from the ideone (I switched to wrong language and I thought the hiccup was wrong too kkk), but the answer was going to be the same as yours

Browser other questions tagged

You are not signed in. Login or sign up in order to post.