seyroku
seyroku

Reputation: 11

Extract the value of a JSON with no keys on PHP

I'm trying to extract the value of a JSON, without a key that gives me a reference.

This is my JSON code:

{"StatTrak™ Dual Berettas | Dualing Dragons (Battle-Scarred)":0.37,"★ StatTrak™ Huntsman Knife | Scorched (Well-Worn)":101.65,"Sticker | iBUYPOWER | DreamHack 2014":11.34,"MP9 | Sand Dashed (Well-Worn)":0.03,"★ Flip Knife | Urban Masked (Field-Tested)":61.74}

The first value is the name and the second one the price. I've got a very long JSON with a lot of name's and prices.

name="StatTrak™ Dual Berettas | Dualing Dragons (Battle-Scarred)"<br>
price="0.37"

Actually don't know how to access the name to extract the other value.

I have the name of the weapons saved on my site from another API. I have to extract the value of this JSON and compare that name with the name the API gave me previously.

Upvotes: 0

Views: 1059

Answers (2)

bartselen
bartselen

Reputation: 26

Assuming I understood you correctly and you want to access values by keys: First of all, I'd axtually recommend using Javascript for this. It doesn't seem like you're parsing any personal or important data that should remain private, so why not let the client do the work instead of giving your server more work to do? Anyhow, as for PHP: First you'll need to decode the json string using the json_decode() function, giving it 2 parameters - the first will be the json string, and the second a simple true boolean, so that it will return an array instead of a json object. The function returns an array, in which each key and value correspond to the name and price in the json list, with the name being the key. Than, to access the value, simply use the array value by key functionality ($arr['weaponname'] would return the price of 'weaponnane', assuming it exists [otherwise you'll get an exception], so you'll need to check that using isset() or array_key_exists()).

Put together, you'll have something along the lines of the following (you'll obviously need to modify this to fit your needs), assuming $weaponname contains the weapon name and $jsonstring the json string:

$price = NULL;
$jsonarr = json_decode($jsonstring, true);
if (isset($jsonarr[$weaponname]))
{
    $price = $jsonarr[$weaponname];
}

If the weapon doesn't exist or it's price is NULL in the array, the $price variable will be NULL.

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

The name is the key:

$array = json_decode($json, true);

foreach($array as $name => $price) {
    echo "$name<br>$price<br>";
}

You see it with a print_r($array):

Array
(
    [StatTrakΓäó Dual Berettas | Dualing Dragons (Battle-Scarred)] => 0.37
    [Γÿà StatTrakΓäó Huntsman Knife | Scorched (Well-Worn)] => 101.65
    [Sticker | iBUYPOWER | DreamHack 2014] => 11.34
    [MP9 | Sand Dashed (Well-Worn)] => 0.03
    [Γÿà Flip Knife | Urban Masked (Field-Tested)] => 61.74
)

Upvotes: 1

Related Questions