Take Multidimensional Array Specific Data

Asked

Viewed 50 times

-1

Hello,

I’m trying to get a specific data from an array but I’m not getting it. I can list up to one dimension but the next one doesn’t... someone gives a help please.

$dados = 'https://api.hgbrasil.com/finance/stock_price?key=53615266&symbol=petr3';
$dadoscont = file_get_contents($dados);
$obj = json_decode($dadoscont,true);
echo "<pre>";
print_r($obj);

So I get the data in the following format:

Array
(
[by] => symbol
[valid_key] => 1
[results] => Array
    (
        [PETR3] => Array
            (
                [symbol] => PETR3
                [name] => Petróleo Brasileiro S.A. - Petrobras
                [region] => Brazil/Sao Paolo
                [currency] => BRL
                [market_time] => Array
                    (
                        [open] => 10:00
                        [close] => 17:30
                        [timezone] => -3
                    )

                [market_cap] => 95695.1
                [price] => 31.42
                [change_percent] => -1.29
                [updated_at] => 2020-01-15 14:11:45
            )

    )

[execution_time] => 0
[from_cache] => 1
)

I can take the first dimension like this:

print_r($obj[results]);

But the one that interests me is the [price]. I have read the tried even with foreach but it did not work.

1 answer

0

You can access this way:

//Montagem do seu array:

$teste = Array("by" => "symbol", 
               "valid_key" => 1,
               "results" => Array (
                   "PETR3" => Array (
                       "symbol" => "PETR3",
                       "name" => "Petróleo Brasileiro S.A. - Petrobras",
                       "region" => "Brazil/Sao Paolo",
                       "currency" => "BRL",
                       "market_time" => Array (
                           "open" => "10:00",
                           "close" => "17:30",
                           "timezone" => "-3"
                        ),
                       "market_cap" => "95695.1",
                       "price" => 31.42,
                       "change_percent" => -1.29,
                       "updated_at" => "2020-01-15 14:11:45"
                    )

            ),
    "execution_time" => 0,
    "from_cache" => 1
);

//Acesso da posição price que você precisa.
$teste['results']['PETR3']['price']

The exit with the var_dump() will be:

float(31.42)

Every position you need to access, just how to do in this example.

Here is a functional example in phpfiddle

Browser other questions tagged

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