Getting variable from one function and pass to another in PHP - php

I have a functiona within a function. Function B gets a value from an API and passes it to function A. However, when I echo the value within Function B it works but it is null when called in function A.
Should I be storing the value in a session variable or DB between loops?
function getFBLikes($postid) {
//Get total number of likes per post
$query = '/likes?summary=1&filter=stream';
$request_likes = BASE_URL
.$postid
.$query
.ACCESS_TOKEN;
$result_likes = json_decode(file_get_contents($request_likes), true);
foreach ($result_likes as $a => $b) {
if(isset($b['total_count'])) {
$likes = $b['total_count'];
echo $likes /* THIS APPEARS AS A CORRECT VALUE */
}
}
}
function getPostDetails($array){
foreach ($array as $a => $b) {
if(isset($b['type'])) {
if(isset($b['object_id'])){
$postid = $b['object_id'];
$shares = $b['shares']['count'];
$type = $b['type'];
getFBLikes($postid);
echo $likes; /* THIS IS NULL */
}
}
}
}

Add
return $likes;
to getFBLikes and
use it like this in getPostDetails
$likes = getFBLikes($postid);

function getFBLikes($postid) {
//Get total number of likes per post
$query = '/likes?summary=1&filter=stream';
$request_likes = BASE_URL
.$postid
.$query
.ACCESS_TOKEN;
$result_likes = json_decode(file_get_contents($request_likes), true);
foreach ($result_likes as $a => $b) {
if(isset($b['total_count'])){
$likes = $b['total_count'];
//ADDED
return $likes;
}
}
}
function getPostDetails($array){
foreach ($array as $a => $b) {
if(isset($b['type'])) {
if(isset($b['object_id'])){
$postid = $b['object_id'];
$shares = $b['shares']['count'];
$type = $b['type'];
//CHANGED
$likes = getFBLikes($postid);
echo $likes; /* THIS SHOULD NO LONGER BE NULL */
}
}
}
}
Should do the trick.
The problem you have here is getPostDetails is taling to getFBLikes,
but getFBLikes is not 'responsing' (returning) anything to you're getPostDetails so when you tried echoing the number of likes it was going to be null because essentially it wasnt being told how many likes there were

You need to have getFBLikes() return a value.
From the docs:
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Sample solution:
in getFBLikes() add:
echo $likes /* THIS APPEARS AS A CORRECT VALUE */
return $likes
in getPostDetails() you can access the value with:
$likes = getFBLikes($postid); /* getFBLikes() will be return a value in $likes

Related

PHP array_filter: if array doesn't have my value return array without changes

To filter an array by key value I do this
//$Myitems this is an array
$make = '3';
$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
$extra_fields_decode = json_decode($Myitems['extra_fields'], true);
$main_value = $extra_fields_decode['1']['value'];
return $main_value == $make;
})
Everything works correctly. But I want to make a condition: if my key value ($make) is not in the array, so that the array is returned without filtering. To return the original array $Myitems. Because next I want to do other things with it. I want to apply array_slice. Exemple:
$FirstItem = array_slice($Myitems, 0, 1);
To begin with, I tried to simply return the original array back like this. But it doesn't work.
$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
$extra_fields_decode = json_decode($Myitems['extra_fields'], true);
$main_value = $extra_fields_decode['1']['value'];
if ($main_value) {
return $main_value == $make;
} else {
return $Myitems;
}
})
How can this problem be solved?
Don't do this in the array_filter() callback. If $make is not in the array, the result of the filter will be an empty array. Check for that and use the original array instead.
$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
$extra_fields_decode = json_decode($Myitems['extra_fields'], true);
$main_value = $extra_fields_decode['1']['value'];
return $main_value == $make;
});
if (count($MyfilterMain) == 0) {
$MyfilterMain = $Myitems;
}
An answer marked as correct is correct. But I decided to do a little on my own. That also works well.
$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
$extra_fields_decode = json_decode($Myitems['extra_fields'], true);
$main_value = $extra_fields_decode['0']['value'];
return $main_value == $make;
});
$MyFilterMainNext = $MyfilterMain ? $MyfilterMain : $Myitems;
In the template
<?php foreach($MyFilterMainNext as $mylist) : ?>
// Your data
<?php endforeach; ?>

recursive function is not working as expected.

public function subchapt()
{
$result = $this->recursive_subchapter_id($level_title);
}
public function recursive_subchapter_id($level_title)
{
$level_data = $this->db->query("SELECT * FROM presto_project_level WHERE level_title ='". $level_title."'")->result_array();
if(count($level_data)>0){
$parentid1 = '';
$leveltitle1 = '';
$parentid1 = trim($level_data[0]['parent_id']);
$leveltitle1 = trim($level_data[0]['level_title']);
if($parentid1 == '0') {
return $leveltitle1;die;
}
else
{
$res = $this->recursive_subchapter_id($parentid1);
return $res;die;
}
}
else{
return $level_title;die;
}
}
every time getting result array is null. i tried directly in url so it was give result array and its count. but while call from other function it was give count of zero.
instead of checking the parentid in the recursive_subchapter_id(), check in subchapt() and then call again recursive_subchapter_id() if it not satisfy the condition.

Putting data base values into array shows error in codeigniter

I am taking data from many tables. I want to display many objects in different places. I got the data from data base, but I want to put the data into an array for useful purpose, but it's not working.
This my controller code:
public function compare_by_business_sectors() {
//print_r($this->input->post());exit;
if ($this->input->post())
{
$solution_array = array();
//print_r (json_encode($business_sectors)); exit;
$business_sectors=$this->home_model->compare_business_sectors_data($this->input->post());
$tab_child_id = "";
$id="";
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id = array();
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
//$solution_array[$id]= $id;
}
print_r($id);
//$this->load->view('compare_by_business_sectors.php');
}
This is my model code:
public function compare_business_sectors_data($sectorid) {
$query = $this->db->select('solutions.*,solution_tabs_child_fields.field_id,solution_tabs_child_fields.tab_child_id,solution_tabs_child_fields.title')
->from('solutions')
//->join('solutions', 'business_sector.sector_id = solutions.business_sector_id',"left")
->join('solution_features','solutions.entry_id = solution_features.entry_id',"left")
->join('solution_tabs_child_fields','solution_features.field_id = solution_tabs_child_fields.field_id')
->where('solutions.business_sector_id', $sectorid['id'])
->get();
return $query->result();
//print_r($query->result());exit;
}
change it as follow and try.
$id_string = "";
$id_array = array();
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id_string = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
print_r($id_string);
print_r($id_array);
First you are assigning string value to $id then, $id will convert to array only if first if() statement execute other wise it will not be a string. So to overcome from this keep $id_array before for loop and you can capture string in another variable.

Escaping issue in building query dynamic function variables

I am developing a CMS which works on template page system in a different approach.
I have this object:
$structure = new stdClass;
$structure->homepage->news->method = 'get_articles_by_page_name';
$structure->homepage->news->lang_key = translate('home_news');
$structure->homepage->news->lang = $lang;
$structure->homepage->news->add_media = true;
$structure->homepage->news->media_type = 'ibs';
$structure->homepage->news->limit = '5';
$structure->homepage->news->order_by = 'a.logical_date';
$structure->homepage->news->asc_des = 'desc';
$structure->homepage->news->result_type = 'result';
This helps to get contents as following:
foreach ($structure as $page_template => $page_contents)
{
// Call Customized Content for Homepage
if($this->data['page_data']->page_view == $page_template) // homepage comes ok.
{
foreach ($page_contents as $view_var_name => $page_cdata)
{
$method = $page_cdata->method; // method names comes
$page_cdata = substr(implode(",",(array) $page_cdata),(strlen($method)+1)) . '\'';
//Returns as expected:
//**'Haberler','tr','1','ibs','5','a.logical_date','desc','result'**
$this->data[$view_var_name] = $this->publish->$method($page_cdata);
vdebug($page_cdata);
}
}
}
It suppose to call them model function of:
function get_articles_by_page_name( $lang_key='',$lang='en',$add_media=true,
media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
However, there is a problem with. When I return to last worked query it says:
SELECT * FROM (`page`) JOIN `page_lang` ON `page`.`id_page` = `page_lang`.`id_page` WHERE `page_lang`.`title` = '\'News\',\'tr\',\'1\',\'ibs\',\'5\',\'a.logical_date\',\'desc\',\'result\''
It souldn't be like this. every thing between commas are parameters of the method function. What cause this, any idea?
Content of get_articles_by_page_name:
function get_articles_by_page_name ($lang_key='',$lang='tr',$add_media=true,$media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
{
// Define variables
$id_page = '';
$result = '';
// Get Page Data
$page_name = $lang_key;
$get_page = $this->vayes->getJoined('page','page_lang','id_page','','',array('page_lang.title'=>$page_name),'row');
if($get_page)
{
$id_page = $get_page->id_page;
$result = $this->publish->get_articles($lang,$id_page,null,false,'',$order_by,$asc_desc,$limit,'result');
}
else
{
$result = array('No id_page specified');
}
return $result;
}
Content of get_articles:
function get_articles($lang='tr',$id_page,$id_article=null,$incl_media=true,$media_type='',$order_by='a.logical_date',$asc_desc='desc',$limit='0',$result_type='result')
{
$this->db->select('*');
$this->db->from('article a');
$this->db->join('article_lang b','b.id_article=a.id_article','left outer');
if($incl_media) {
$this->db->join('article_media c','c.id_article=b.id_article','left outer');
$this->db->join('media d','d.id_media=c.id_media','left outer');
}
if($id_article == null) { $this->db->where('a.id_page',$id_page); }
else /*------------->*/ { $this->db->where('a.id_article',$id_article); }
$this->db->where('b.lang',$lang);
$this->db->where('b.online',1);
if(($incl_media == true) AND $media_type != '' ) $this->db->where('c.usage',$media_type);
// Order Results
$this->db->order_by($order_by,$asc_desc);
// Limit Results
if ($limit) $this->db->limit($limit);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->$result_type();
$query->free_result();
return $result;
}
return false;
}
try stripslashes()
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL. So using stripslashes() on an array you will need to do it recursively;
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);

I want to take a single value from one function and use it in another function - codeigniter/php/mysql

I want to take a value from a query in one function and use it for multiplication within another function.
Here i have a function producing the number 3:
function insert() {
$siteid = 1;
$field = 3;
$time = "2011-10-11 15:04:56";
$this->db->select('Offset_value', 1)
->from('offset')
->where('siteid', $siteid)
->where('Offset_field', $field)
->where('time <', $time);
$query = $this->db->get()->result_array();
foreach ($query as $row) {
echo $row['Offset_value'];
}
return $query;
}
At the moment this is just set to display the number 3 but i need that value to be stored in a variable of some sort and load it into this function:
function get_sap_estimate() {
$kwp = 5;
$direction = 34;
$tilt = 60;
$month = 4;
$sap_shadingid = 2;
$this->db->select('derating_factor')
->from('sap_shading')
->where('id', $sap_shadingid);
$query = $this->db->get()->result_array();
$query = $query[0];
$dr = $query['derating_factor'];
$this->db->select("kwh * $dr * $kwp AS kwhdata")
->from('expected_kwh')
->where('direction', $direction)
->where('tilt', $tilt)
->where('month', $month);
$query2 = $this->db->get()->result_array();
return $query2;
}
Can this be done and how??
Thanks
function A(){
return "value";
}
functionB(){
var value = A(); // here is your array
var value_you_need = value[0]['Offset_value'];
}
If they are both in the same class (read: model file) write
var $_var;
before any methods are made. Then inside one of your methods type
$this->_var = $stuff;
to give this var a value. Then to use that value type
$new_stuff = $this->_var;
If they're not in the same class, you could try calling the first method inside of the second.

Categories