tags:

views:

37

answers:

2

So currently I am doing this..

function get_info($data)
{
    $json = file_get_contents("http://site.com/".$data.".json");
    $output = json_decode($json, true);
    return $output;
}

which is fine and returns everything like this:

array(1) { ["allocation"]=> array(20) { ["carrier_ocn"]=> string(4) "6664" ["available_on"]=> NULL ["status"]=> string(9) "allocated" ["access_type"]=> string(8) "wireless" ["ratecenter"]=> string(9) "CHARLOTTE" ["lat"]=> float(35.2270869) ["contaminations"]=> NULL ["city"]=> string(9) "CHARLOTTE" ["lng"]=> float(-80.8431267) ["current_on"]=> string(10) "2010-04-28" ["block_code"]=> NULL ["npa"]=> int(704) ["geo_precision"]=> int(4) ["nxx"]=> int(291) ["assigned_on"]=> NULL ["country"]=> string(2) "US" ["region"]=> string(2) "NC" ["ratecenter_formatted"]=> string(9) "Charlotte" ["carrier"]=> string(20) "SPRINT SPECTRUM L.P." ["effective_on"]=> NULL } }

How can I make that return only selected values like "ratecenter_formatted". I just want to get "Charlotte" from the above dump. How would I do this?

Thank you in advance!

+2  A: 

Hmmm, just fish it out from the array? json_decode() on a JSON array will give you a PHP array that you can use just like any other array in PHP (in this case an associative one).

$output = get_info($data);
echo $output['allocation']['ratecenter_formatted'];
BoltClock
+1 you were just 2 seconds faster :)
jek
Thank you for the response, however I don't understand. What about file_get_contents? That code isn't working..
@user: What do you mean by it isn't working? Is the JSON no longer parsing correctly, do you no longer obtain the contents of the file?
BoltClock
Nevermind, I got your code working now. Thank you, now I will know how to do this when I run into this in the future!
A: 

You would still need to decode the entire JSON string to get single values from it, there's no way to decode only certain values.

You could just return the values you want in the php function:

function get_info($data)
{
    $json = file_get_contents("http://site.com/".$data.".json");
    $output = json_decode($json, true);
    return array(
        'ratecenter_formatted' => $output['allocation']['ratecenter_formatted']
    );
}
Luca Matteis
Thank you for the information