ESipalis
ESipalis

Reputation: 431

PHP reading json data

I'm new to PHP and web programming at all.I am trying to read some json data from steam API.

Data: http://pastebin.com/hVWyLrfZ

I managed to get to single objects(I believe?).

This is my code:

<?php
    $url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
    $JSON = file_get_contents($url);
    $data = json_decode($JSON);
    $heroes = reset(reset($data));

    //var_dump($heroes);
    $wat = reset($heroes);
    $antimage = array_values($heroes)[0];
    var_dump($antimage);
?>

I want data to be in array like this:

id => name

I mean, array keys should be ids and values should be hero names.

Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?

Upvotes: 0

Views: 66

Answers (2)

CodeBoy
CodeBoy

Reputation: 3300

A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...

$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
    $myResult[$nameId['id']] = $nameId['name'];
}

(No need to do any reset calls; that's a weird way to get the first element of an array)

Note, for this to work, you must apply the tip by @RamRaider

$data = json_decode($JSON, true);

in order for json_decode to return arrays, not StdClass.

Upvotes: 2

Ibrahim
Ibrahim

Reputation: 2072

You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.

$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);

$ids = array_map(function($a) {
    return $a['id'];
}, $data['result']['heroes']);

$names = array_map(function($a) {
    return $a['name'];
}, $data['result']['heroes']);

$heroes = array_combine($ids, $names);

print_r($heroes);

Upvotes: 3

Related Questions