Array return at the end one value - php

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;
}

Related

Using a delimited string, how do I get an array item relative to the parsed string?

Given a string in the format of "one/two" or "one/two/three", with / as delimiters, I need to get the value (as a reference) in a 2d array. In this specific case, I'm accessing the $_SESSION variable.
In the SessionAccessor::getData($str) function, I don't know what to put in there to make it parse the delimited string and return the array item. The idea is I won't know which array key I'm accessing. The function will be generic.
class SessionAccessor {
static &function getData($str) {
// $str = 'one/two/three'
return $_SESSION['one']['two']['three'];
}
}
/** Below is an example of how it will be expected to work **/
/**********************************************************/
// Get a reference to the array
$value =& SessionAccessor::getData('one/two/three');
// Set the value of $_SESSION['one']['two']['three'] to NULL
$value = NULL;
Here's the solution provided by #RocketHazmat here at StackOverflow:
class SessionAccessor {
static function &getVar($str) {
$arr =& $_SESSION;
foreach(explode('/',$str) as $path){
$arr =& $arr[$path];
}
return $arr;
}
}
From what you've described, it sounds like this is what you're after;
&function getData($str) {
$path = explode('/', $str);
$value = $_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
EDIT
To also allow for the values to be set, it would be best to use a setData method. This should hopefully do what you hoped for;
class SessionAccessor {
static function getData($str) {
$path = explode('/', $str);
$value = $_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
static function setData($str, $newValue) {
$path = explode('/', $str);
$last = array_pop($path);
$value = &$_SESSION;
foreach ($path as $key) {
if (!isset($value[$key])) {
$value[$key] = array();
}
$value = &$value[$key];
}
$value[$last] = $newValue;
}
}

Access multidimensional array with a path-like string

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]];
}

In CodeIgniter how can i pass an array type argument to a controller from url

//let my controller be C and method be:
function X($array){}
//And my url to call it is:
localhost/mysite/C/X/array
Well i tried it but it returns 400-Bad Request response.
Does anyone know how to do it? Quick response will help me a lot//Thanx
localhost/mysite/C/X/?array=1&&?array=2....
$array = $this->input->get('array');
or
localhost/mysite/C/X/1,2,3,4,5
$array = explode(',' $this->uri->segment(n));
// in app/config/config.php
$config['permitted_uri_chars'] = 'a-z 0-9~%.:,_-';
My variant for array in url (/tours/novogodniye-turi/visa=yes;duration=small;transport=4,7,6,2/)
if ( ! function_exists('filter_parse_segment'))
{
function filter_parse_segment($segment, $merge_to_get = FALSE)
{
if(empty($segment))
{
return FALSE;
}
$parameters = explode(";", (string)$segment);
if(empty($parameters))
{
return FALSE;
}
$parameters_array = array();
foreach($parameters as $parameter)
{
if(empty($parameter))
{
continue;
}
$parameter = explode("=", $parameter);
if( ! isset($parameter[0], $parameter[1]) or empty($parameter[0]))
{
continue;
}
if(strpos($parameter[1], ','))
{
$parameter[1] = explode(",", $parameter[1]);
}
$parameters_array[$parameter[0]] = $parameter[1];
}
if($merge_to_get === TRUE)
{
$_GET = array_merge($_GET, $parameters_array);
}
return $parameters_array;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('filter_collect_segment'))
{
function filter_collect_segment($array, $suffix = '', $remove = array())
{
if(empty($array) || ! is_array($array))
{
return '';
}
$segment_str = '';
foreach ($array as $key => $value)
{
if(empty($key) || in_array($key, (array)$remove))
{
continue;
}
if( ! $segment_str == '')
{
$segment_str = $segment_str.';';
}
if( ! is_array($value))
{
$segment_str = $segment_str.$key.'='.$value;
continue;
}
if(empty($value))
{
continue;
}
$parsed_value = '';
foreach ($value as $item)
{
if( ! $parsed_value == '')
{
$parsed_value = $parsed_value.',';
}
if(is_array($item) || empty($item))
{
continue;
}
$parsed_value = $parsed_value.$item;
}
$segment_str = $segment_str.$key.'='.$parsed_value;
}
if($segment_str != '')
{
$segment_str = $segment_str.$suffix;
}
return $segment_str;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('filter_key'))
{
function filter_key($filter_array, $key, $value = NULL)
{
if( ! isset($filter_array[$key]))
{
return;
}
if($value == NULL)
{
return $filter_array[$key];
}
if( ! is_array($filter_array[$key]) && $filter_array[$key] == (string)$value)
{
return $value;
}
if(is_array($filter_array[$key]) && in_array($value, $filter_array[$key]))
{
return $value;
}
return FALSE;
}
}
If you want the solution in the pretty nice URL then you have to loop the array first and then concatenate the elements with some - dash or + plus signs like this;
$array = array(1,2,3,4);
$string = "";
foreach($array as $value){
$string .= $value."-";
}
$string = rtrim($string, "-");
redirect(base_url()."get_products?param=".$string);
And on the next page just get the param and use explode() function with - dash sign to create the array again.
try your url like this
if value you have to pass is
[1,2,3,2]
then
localhost/mysite/index.php/C/X/1,2,3,2
In a simple way you can make the array a string with some special character in between the values of the array.
Then in the landing page you can split the string with the special character and get the array again.
If the values are [1,2,3,4], then make it using a loop "1,2,3,4".
Then pass the string.
In teh landing page split the string with "," and you will again get the array.
Hope it helps you.
Thanks
Why don't you use uri segments for array? You can count uri segments and could use them. Even u could check how many arrays already there.
url.com/1/2/3
http://ellislab.com/codeigniter/user-guide/libraries/uri.html
Note: uri segment doesnt work on main controller index function, you have to define another function than index for example: I don't know what it happens but i think because of htaccess file I'm using do remove index.php.
url.com/uri_segment_controller/go/1/2/3

Return in recursive function php

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;

Php variable result

$name= path1
$key= key1
public static function getpath($name, $key)
{
if (!self::is_valid($name, $key)) return false;
$path = '/var/lib/fdata/'.$name.'/'.$key;
if (!is_file($path)) return false;
return $path;
}
public static function get($name, $key)
{
$path = self::getpath($name, $key);
if ($path === false) return false;
return file_get_contents($path);
}
$configmap = unserialize(fdata::get('base', 'key'));
The questions is:
if variable $path = self::getpath($name, $key); then $path = ? and what mean self::
if variable $configmap = unserialize(fdata::get('base', 'key')); then $configmap = ? and what mean fdata::
1) self::getpath(...) should return a boolean value or a string. self:: refers to a current class.
2) Here's the man for unserialize
3)
fdata:: denotes the namespace fdata or perhaps a class.

Categories