We are trying to call the same function from within the function but it won't work.
We belive that there is a &$result variable that should be placed somewhere , we have seen it in other parts of our code that another person has written, but we don't know where and how it works.
Could someone please explain?
Here is our code if you want to have a look:
$parentID = $_POST['id'];
$choosenCategory = $_POST['choosenCategory'];
$count = 0;
function count_child($parentID, $choosenCategory){
foreach($parentID as $thisID){
foreach($_SESSION['items'][$thisID]['Children'] as $ChildID){
$DatabaseID = $ChildID;
$ItemCategory = $_SESSION['items'][$DatabaseID]['ItemCategory'];
$ItemName = $_SESSION['items'][$DatabaseID]['ItemName'];
$ItemStatus = $_SESSION['items'][$DatabaseID]['ItemStatus'];
$ParentID = $_SESSION['items'][$thisID]['DatabaseID'];
$Children = $_SESSION['items'][$DatabaseID]['Children'];
$Dependencies = $_SESSION['items'][$DatabaseID]['Dependencies'];
if($ItemCategory == $choosenCategory){
$count++;
}
if($ItemCategory !== "RWP" && $ItemCategory !== "US" && $levels === "all"){
$array = array();
count_child($ChildID, $choosenCategory);
}
}
}
}
count_child($parentID, $choosenCategory);
$json = json_encode($count);
echo $json;
It always output 0, regardless of what input we give.
Try to return $count from the function;
Like this:
$parentID = $_POST['id'];
$choosenCategory = $_POST['choosenCategory'];
function count_child($parentID, $choosenCategory){
$count = 0;
foreach ($parentID as $thisID){
$aChild = &$_SESSION['items'][$thisID]['Children'];
foreach ($aChild as $ChildID){
$DatabaseID = $ChildID;
$ItemCategory = $_SESSION['items'][$DatabaseID]['ItemCategory'];
$ItemName = $_SESSION['items'][$DatabaseID]['ItemName'];
$ItemStatus = $_SESSION['items'][$DatabaseID]['ItemStatus'];
$ParentID = $_SESSION['items'][$thisID]['DatabaseID'];
$Children = $_SESSION['items'][$DatabaseID]['Children'];
$Dependencies = $_SESSION['items'][$DatabaseID]['Dependencies'];
if ($ItemCategory == $choosenCategory){
$count++;
}
if ($ItemCategory !== "RWP" && $ItemCategory !== "US" && $levels === "all"){
$array = array();
paint_child($ChildID, $choosenCategory);
}
}
}
return $count;
}
$count = count_child($parentID, $choosenCategory);
$json = json_encode($count);
echo $json;
Depending on the php version and which datatype you are using, php creates a copy of your data when you call the function. that copy is used within that function. when you are now modify the data then the copy is modify. Later when your call is finished, the copy will be deleted (in each function call in every recursion step). That & operation avoids a copy and sends a reference. No copy will be created. The reference operator can used in function parameters also at return values, but it's more common in function parameters.
Related
hi i have many data files in json format in a folder.
now i want to search a filed in them .my search word maybe not exist in some of them and may be exist in one of them files.
i have read this function and if not exits in a file i call the function to read another file.
when i echo the result show me and works fine but return not working and no data returned.
function get_shenavari_in_files($search,$type)
{
static $counter =1 ;
$darsadi = 0;
$find = false;
$file_name = get_files_in_dir(); // make an array of file names
$file_number = count($file_name)-$counter ;
$file="files/" .$file_name[$file_number];
$file_data = read_json($file);
for($i = 0 ; $i<count($file_data) ; $i++)
{
if($file_data[$i][$type] == $search )
{
$darsadi = $file_data[$i]['darsadi'] ;
$find = true;
echo $darsadi ; //this works and show the data
return $darsadi; // this is my problem no data return.
break;
}
}
if($find == false)
{
$counter ++;
get_shenavari_in_files($search,$type);
}
}
var_dump(get_shenavari_in_files('Euro','symbol')); //return null
Once you recurse into get_shenavari_in_files, any found value is never returned back to the inital caller, i.e. instead of
if($find == false)
{
...
get_shenavari_in_files($search,$type);
}
you simply need to prepend the function call with a returnstatement
if($find == false)
{
...
return get_shenavari_in_files($search,$type);
}
Having said that, I would try a much simpler (and thereby less error-prone) approach, e.g.:
function get_shenavari_in_files($search, $type) {
$files = glob("files/*.json"); // Get names of all JSON files in a given path
$matches = [];
foreach ($files as $file) {
$data = json_decode(file_get_contents($file), true);
foreach ($data as $row) {
if (array_key_exists($type, $row) && $row[$type] == $search) {
$matches[$file] = $search;
}
}
}
return $matches;
}
This way, you would be able to eliminate the need for a recursive call to get_shenavari_in_files. Also, the function itself would become more performant because it doesn't have to scan the file system over and over again.
Here's the whole script.php:
require_once('../app/Mage.php'); Mage::init();
$fbn = ($_GET['fbn']) ? trim(htmlencode($_GET['fbn'])) : null;
if (is_null($fbn)) die("specify filebasename in url (?fbn= )");
$file = __DIR__."/csv/{$fbn}.csv"; echo $file; var_dump($_GET);
class UpdateProductGallerySelects
{
public function __construct($file, $num = 0)
{
if (!file_exists($file)) die('no good file');
$csv = array_map('str_getcsv', file($file));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
}); array_shift($csv);
foreach ($csv as $row) $this->updateProduct($row);
}
private function updateProduct($r)
{
$p = null; print_r($r);
$p = Mage::getModel('catalog/product')->load($r['sku'], 'sku');
$g = $p->getMediaGalleryImages('images');
$ct = count($g); echo $p->getName()." {{$ct}}\n";
}
}
$set = new UpdateProductGallerySelects($file, 10);
This runs up to the first die(), apparently, which does print if $fbn is null.
Please tell me what's wrong.
You must check your $_GET['fbn'] as it seems you are not getting anything in this variable. You must pass some value in it and then check.
I've got a little problem with recursive function output. Here's the code:
function getTemplate($id) {
global $templates;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
$arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
}
return $arr['text'];
}
The problem is that that function returns a value on each iteration like this:
file.exe
category / file.exe
root / category / file.exe
And I need only the last string which resembles full path. Any suggestions?
//UPD: done, the problem was with the dot in $arr['text'] .= str_replace
Try this please. I know its using global variable but I think this should work
$arrGlobal = array();
function getTemplate($id) {
global $templates;
global $arrGlobal;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
array_push($arrGlobal, getTemplate($arr['parentId']));
}
return $arr['text'];
}
$arrGlobal = array_reverse($arrGlobal);
echo implode('/',$arrGlobal);
Try this,
function getTemplate($id) {
global $templates;
$arr = $templates[$id-1];
if($arr['parentId'] != 0) {
return $arr['text'] .= str_replace($arr['attr'], $arr['text'], getTemplate($arr['parentId']));
}
}
Give this a try:
function getTemplate($id, array $templates = array())
{
$index = $id - 1;
if (isset($templates[$index])) {
$template = $templates[$index];
if (isset($template['parentId']) && $template['parentId'] != 0) {
$parent = getTemplate($template['parentId'], $templates);
$template['text'] .= str_replace($template['attr'], $template['text'], $parent);
}
return $template['text'];
}
return '';
}
$test = getTemplate(123, $templates);
echo $test;
I would like to assign a variable that is the first not null element from another set of variables. Much like the conditional assignment in ruby ||=. For example:
<?php
$result = null;
$possibleValue1 = null;
// $possibleValue2 not defined
$possibleValue3 = 'value3';
if (isset($possibleValue1) && !is_null($possibleValue1)) {
$result = $possibleValue1;
} else if (isset($possibleValue2) && !is_null($possibleValue2)) {
$result = $possibleValue2;
} else if (isset($possibleValue3) && !is_null($possibleValue3)) {
$result = $possibleValue3;
}
Is there a way to do this simply in php, like so (if possible, I would like to avoid creating a function and just use functions from the php library):
$result = firstNotNull(array($possibleValue1, $possibleValue2, $possibleValue3));
I think the shortest way is:
$result = current(array_filter(array($possibleValue1, $possibleValue2, $possibleValue3)));
If all $possibleValues are definitely set:
$possibleValues = array($possibleValue1, $possibleValue2, ...);
If they may not be set:
$possibleValues = compact('possibleValue1', 'possibleValue2', ...);
Then:
$result = reset(array_filter($possibleValues, function ($i) { return $i !== null; }));
Do not know about such a function in PHP but why not creating Your own?
function getFirstNotNullValue($values = array()) {
foreach($values as $val)
if($val) return $val;
return false;
}
I have the following PHP code:
<?php
//code above
$pic_1 = $afil['image_1'];
$pic_2 = $afil['image_2'];
$pic_3 = $afil['image_3'];
$pic_4 = $afil['image_4'];
$pic_5 = $afil['image_5'];
$pic_6 = $afil['image_6'];
$pic_7= $afil['image_7'];
$pic_8 = $afil['image_8'];
$pic_9 = $afil['image_9'];
$pic_10 = $afil['image_10'];
if ($pic_1 = "")
{
$pic_1 = //defaultpic - to be defined, same as below
}
if ($pic_2 = "")
{
$pic_2 = //defaultpic
}
?>
Rather than repeat these "if" statements for each picture (up until $pic 10) i just wondered if somebody could point out a more elegant and efficient way of doing it. I am quite new to php and this is a new situation i have encountered. Thanks a lot in advance.
Use arrays and loop through them with just 1 if statement, like this,
foreach($afil as $k => $v) {
if(empty($v))
$afil[$k] = ...//default pic
}
Or, if you are keen to have an additional array $pics (for future use maybe),
foreach($afil as $k => $v) {
$pics[$k] = $v;
if(empty($v))
$pics[$k] = ...//default pic
}
Also, = is an assignment operator. For comparison (or condition check), you need to use == or === (type safe).
Edit:
$afil = mysql_query(...);
while($row = mysql_fetch_array($afil)) {
//In here, say you create an array $result_rows with all the rows
$result_rows[] = $row;
}
Then, use $result_rows in the foreach.
Arrays is your golden solution:
$pic = array('image_1', 'image_2', 'image_3'....);
for ($i = 0; $i < count($pic); $i++){
if ($pic[$i] == ""){
$pic[$i] = //defaultpic -
}
}