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;
Related
I want to pass a variable to a language file. I have created MY_language.php in application/core/MY_language.php.
class MY_Language extends CI_Lang
{
public function __construct()
{
parent::__construct();
}
function line($line, $params = null)
{
$return = parent::line($line);
if ($return === false) {
return "!-- $line --!";
} else {
if (!is_null($params)) {
$return = $this->_ni_line($return, $params);
}
return $return;
}
}
private function _ni_line($str, $params)
{
$return = $str;
$params = is_array($params) ? $params : array($params);
$search = array();
$cnt = 0;
foreach ($params as $param) {
$search[$cnt] = '/\\$' . ($cnt + 1) . '/';
$cnt++;
}
$return = preg_replace($search, $params, $return);
return $return;
}
}
This file must override the CodeIgniter line() function and accept an array of parameters as input, and insert into string language everywhereIi have type $ in my language text.
$lang['delete'] = "$name was deleted";
The result of the above code is:
sam was deleted
in codeigniter 3 the language your core language file must be PREFIX_lang
Since you are adding parameters to the line() function you are unable to override it.
Use a different name like magic_line()
what is the best way to put parents value in the same array ( Concate ) as this code just return one value
public function divisionParent($name)
{
$path = array();
$path[] = $name;
$div = CsiCategory::where('name', $name)->first();
$parent_id = $div->parent_id;
if ($parent_id != 0) {
$name = CsiCategory::where('id', $parent_id)->first();
$this->divisionParent($name->name);
}
return $path;
}
Something like this maybe?
public function divisionParent($name, $path = [])
{
// Append to $path arr.
array_push($path, $name);
// Get division by name.
$div = CsiCategory::where('name', $name)->first();
// Check for existing parent division by id.
if (isset($div)) {
if ($div->parent_id != 0) {
$divParent = CsiCategory::where('id', $div->parent_id)->first();
}
}
return isset($divParent) ? $this->divisionParent($divParent->name, $path) : $path;
}
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.
I have a function called get_config() and an array called $config.
I call the function by using get_config('site.name') and am looking for a way to return the value of $config so for this example, the function should return $config['site']['name'].
I'm nearly pulling my hair out - trying not to use eval()! Any ideas?
EDIT: So far I have:
function get_config($item)
{
global $config;
$item_config = '';
$item_path = '';
foreach(explode('.', $item) as $item_part)
{
$item_path .= $item."][";
$item = $config.{rtrim($item_path, "][")};
}
return $item;
}
This should work:
function get_config($config, $string) {
$keys = explode('.', $string);
$current = $config;
foreach($keys as $key) {
if(!is_array($current) || !array_key_exists($key, $current)) {
throw new Exception('index ' . $string . ' was not found');
}
$current = $current[$key];
}
return $current;
}
you could try something like...
function get_config($item)
{
global $config;
return $config[{str_replace('.','][',$item)}];
}
Inside your get_config function, you can parse the string using explode function in php
function get_config($data){
$pieces = explode(".", $data);
return $config[$pieces[0]][$pieces[1]];
}
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;
}