Accessing array keys with PHP loop

I'm good with PHP, but my brain is slow working with arrays.

This is an API, returning a JSON I already encoded into an array.

http://data.gate.io/api2/1/tickers

Let's call it $myarray

$index=1;
foreach($myarray as $key => $value)
    {
    echo $index." ".$value['last']."<BR>";
    $index++;
    }

Everything works ok, I can access all the fields inside the sub-arrays; but I can not access the "name" of the subarray ("btc_usdt" for example). If I use $value[0], I got a null. If I use $value alone, I got the string "array". Is there any way I can access that info?

Upvotes: 0

Views: 68

Answers (5)

Ravi Singh
Ravi Singh

Reputation: 55

If you are still confused with the above working example then I have another solution here:

$myarray = json_decode(file_get_contents('http://data.gate.io/api2/1/tickers'), true);
$index = 0;
$newarray = [];
foreach ($myarray as $key => $value) {
$newarray[$index] = $value;
$newarray[$index]['name'] = $key;
$index++;
}
echo '<pre>';print_r($newarray);exit;

Now the name attribute is shifted to the sub-array and you can easily iterate newly generated array i.e. $newarray.

Hope it helps!

Upvotes: 0

Brian Otto
Brian Otto

Reputation: 56

The "name" is stored in $key. Here is a working example ...

<?php
$myarray = json_decode(file_get_contents('http://data.gate.io/api2/1/tickers'), true);

$index = 1;
foreach ($myarray as $key => $value) {
    echo $index . " " . $key . " " . $value['last'] . "<BR>";
    $index++;
}
?>

Upvotes: 1

Ice76
Ice76

Reputation: 1130

This is tested and working for the link you provided. I think you are not formatting the JSON data correctly.

$data = file_get_contents( 'http://data.gate.io/api2/1/tickers' );
$formattedData = json_decode( $data, true );
$index = 1;
foreach($formattedData as $key => $value)
{
    echo $index . " name: {$key}, last: " . $value['last'] . "<BR>";
    $index++;
}

The name of the array is the key of the value.

Upvotes: 0

jh1711
jh1711

Reputation: 2328

Since your code is working, I assume you converted it with json_decode(..., true);. Then the answer is really simple. The name of the current sub-array is stored in the $key variable.

Upvotes: 1

Luffy
Luffy

Reputation: 1026

Because each sub-arrays are stdClass objects, you can do it like this

$index=1;
foreach($myarray as $key => $value) {
    echo $index . " ". $value->last . "<BR>";
$index++;
}

Upvotes: 0

Related Questions