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!
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.
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'];
Related
i have code..
<?php
function word()
{
$arr = array("/c/","/b/","/c/");
echo $arr[array_rand($arr)];
}
$text = "a";
if(preg_match("$word()", $text)) {
$result = "found";
}else{
$result = "not found";
}
echo $result;
?>
how to call function word(); into preg_match.
I want to randomly search the words in preg_match.
I tried but it didn't work.
how to fix this code.
Thanks
If you make your function word() return the random string instead of echoing it you can use it as any value by calling the function.
function word() {
$arr = array("/c/","/b/","/c/");
return $arr[array_rand($arr)];
}
if( preg_match(word(), $text) ) {
$result = "found";
}
else {
$result = "not found";
}
echo $result;
If it makes it more clear, this is the same as storing the result from the function in a variable and use that.
These are all the same:
// Writing the pattern in place.
preg_match("/a/", $text);
// Storing it in a variable before use.
$to_match = "/a/";
preg_match($to_match, $text);
// Storing it in a variable where the value is returned from a function.
$to_match = word();
preg_match($to_match, $text);
// Using a function directly in the call to `preg_match`.
preg_match(word(), $text);
If I use return in my function, I will get only one value.
If I use echo, I get all the values. I don't get it.
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
return ''.ucfirst($url_final).'';
}
Seems that I can't insert the echoes into a database, they appear blank if I run the function.
What to do?
When you have a return the code would not execute further. Generate the whole data, then return that data.
You can either built an array. Like -
$urls= array();
foreach($matches[0] as $matchbun)
{
.....
$urls[]= ucfirst($url_final);
}
return $urls;
Or You can generate a string. Like -
$urls= '';
foreach($matches[0] as $matchbun)
{
.....
$urls.= ucfirst($url_final);
}
return $urls;
Well, if you use return, you'll exit from that function on first iteration.
If you use echo, you are not exiting the function, you are echoing every iteration of the foreach loop.
Take return out of loop. and put data you want to return in a variable. Like this:
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
$myNewVariable .= $url_final;
}
return $myNewVariable;
I am getting this:
How do I receive the count. I've tried a couple of ways like $r->count and $r->count();
This is a gist.
// Results is an SplObjectStorage object where each request is a key
foreach ($results as $request) {
// Get the result (either a ResponseInterface or RequestException)
$result = $results[$request];
if ($result instanceof ResponseInterface) {
// Interact with the response directly
$r = $result->getBody();
echo $r;
} else {
// Get the exception message
echo $result->getMessage();
}
}
Since that's a JSON string, You could decode it into an object using json_decode
$r = $result->getBody();
$response=json_decode($r);
echo $response->count;
Fiddle
I found the answer myself. I had to use get_object_vars(). Converts an object to array.
$r = $result->getBody();
$response=json_decode($r);
$s = get_object_vars($response);
dd($s->count);
I want to use a function to load my news feed on my website dynamically from my database, I have created a function with variables for the type of post, from a specific user etc, and I want to run a while() loop to return each and every post as you would usually, how can this be done within a function though? I tried running the loop and setting the content I want to display in a single variable, which it then returns within that loop, I was hoping it would then run a return each time within the loop and the function would echo each out one by one, when I think about it logically, that obviously wouldn't happen, so could someone explain how this would be achieved?
Example (similar) code:
Accessing the function:
<?php echo getNews(); ?>
The function:
<?php function getNews(){
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
return $return;
}
?>
Return stops function executing. You could try something like
function getNews(){
$html = null;
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
$html .= $return;
}
return $html;
}
The return should be used out side of the loop
Try this function
<?php function getNews()
{
$return =array()
while($row = mysql_fetch_array($result))
{
$return[] = "Looped data";
}
return $return;
}
?>
With the first return the function breaks and so only the first row is fetched. You can temporarily save the data in an array and return it. When echoing you can then implode() it.
function getNews(){
//query stuff
$result = array();
while($row = mysql_fetch_array($result)){
$result[] = "looped data";
}
return $result;
}
echo implode("<br>\n", getNews());
Getting an array returned can be more useful in the future. Also the function name is more descriptive in my opinion. It doesn't say concat/etc, only get.
You can't use function to return with each loop. Alternatively either you can save the result created in loop to a variable or an array and return the variable/array. Example using variable is:
<?php function getNews() {
//query stuff
$return = "";
while($row = mysql_fetch_array($result)) {
$return .= "Looped data";
}
return $return;
}
?>
If your purpose is just echo the result than do it in function itself without using variable. Array would be better if you want to process something with result.
I have the following PHP code which works out the possible combinations from a set of arrays:
function showCombinations($string, $traits, $i){
if($i >= count($traits)){
echo trim($string) . '<br>';
}else{
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
showCombinations('', $traits, 0);
However, my problem is that I need to store the results in an array for processing later rather than just print them out but I can't see how this can be done without using a global variable.
Does anyone know of an alternative way to achieve something similar or modify this to give me results I can use?
Return them. Make showCombinations() return a list of items. In the first case you only return one item, in the other recursive case you return a list with all the returned lists merged. For example:
function showCombinations(...) {
$result = array();
if (...) {
$result[] = $item;
}
else {
foreach (...) {
$result = array_merge($result, showCombinations(...));
}
}
return $result;
}
In addition to the other answers, you could pass the address of an array around inside your function, but honestly this isn't nearly the best way to do it.
Using the variable scope modifier static could work. Alternatively, you could employ references, but that's just one more variable to pass. This works with "return syntax".
function showCombinations($string, $traits, $i){
static $finalTraits;
if (!is_array($finalTraits)) {
$finalTraits = array();
}
if($i >= count($traits)){
//echo trim($string) . '<br>';
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
return $finalTraits;
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
echo join("<br>\n",showCombinations('', $traits, 0));
Of course, this will work as expected exactly once, before the static nature of the variable catches up with you. Therefore, this is probably a better solution:
function showCombinations($string, $traits, $i){
$finalTraits = array();
if($i >= count($traits)){
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
$finalTraits = array_merge(
$finalTraits,
showCombinations("$string$trait", $traits, $i + 1)
);
}
}
return $finalTraits;
}
although the solution by Lukáš is the purest as it has no side effects, it may be ineffective on large inputs, because it forces the engine to constantly generate new arrays. There are two more ways that seem to be less memory-consuming
have a results array passed by reference and replace the echo call with $result[]=
(preferred) wrap the whole story into a class and use $this->result when appropriate
the class approach is especially nice when used together with php iterators
public function pageslug_genrator($slug,$cat){
$page_check=$this->ci->cms_model->show_page($slug);
if($page_check[0]->page_parents != 0 ){
$page_checks=$this->ci->page_model->page_list($page_check[0]->page_parents);
$cat[]=$page_checks['re_page'][0]->page_slug;
$this->pageslug_genrator($page_checks['re_page'][0]->page_slug,$cat);
}
else
{
return $cat;
}
}
this function doesnt return any value but when i m doing print_r $cat it re
store the results in a $_SESSION variable.