tags:

views:

16

answers:

2

I'm trying to have this function return multiple results in array(?).

So basically instead of running lookup("354534", "name"); and lookup("354534", "date"); mutiple times for different results, how can I return both name & date from that function, then echo it out so I only have to use the function once?

    function lookup($data, $what)
 {
  $json = file_get_contents("http://site.com/".$data.".json");
  $output = json_decode($json, true);  
  echo $output['foo'][''.$what.''];
 }

Thanks!

A: 

Have the function return the whole JSON result:

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

then you can do

$result = lookup("354534");

echo $result["name"];
echo $result["date"];

This is really a good idea, because otherwise, you'll make the (slow) file_get_contents request multiple times, something you want to avoid.

Pekka
Yeah, that's why I didn't want to run it multiple times, and it made no sense doing so. I just didn't know how to do it until now, thanks pekka!
Actually, when I run the code I get Message: Undefined index: date. Any reason why?
@user the json probably doesn't contain a field named "date" in that case
Pekka
@pekka, I just verified it does contain "date" by going to the json url. It worked the previous (multiple time) way I was doing it, but it's not working this way
@user can you do a `print_r($output);`
Pekka
@user ah sorry, I overlooked the "foo" in your question. I updated my answer
Pekka
A: 

substitue echo in your function with return, and return the entire array:

function lookup($data){
  ...
  return $output;
  }

...

$results = lookup($someData);
echo $results['name'] . $results['date'];
fredley