Jump to content

[SOLVED] How to you explode a string and use each part in assoc array?


maexus

Recommended Posts

So, lets say you have the following string:

 

$string = "a__b__d__z";
$string = explode('__', $string);

 

What I want to do is access a variable like this:

 

$array[$string[0]][$string[1]][$string[2]][$string[3]];

 

I have been using a switch but this is ugly and only allows for as much levels as I put in the switch:

 

public function get($variable){
		$variable = explode('__', $variable);
		switch(count($variable)){
			case 1: #group
			return (isset($this->settings[$variable[0]])) ? $this->settings[$variable[0]] : false;
			break;

			case 2: #variable
			return (isset($this->settings[$variable[0]][$variable[1]])) ? $this->settings[$variable[0]][$variable[1]] : false;
			break;

			case 3: #subvariable
			return (isset($this->settings[$variable[0]][$variable[1]][$variable[2]])) ? $this->settings[$variable[0]][$variable[1]][$variable[2]] : false;
			break;
		}
	}

 

Don't worry about the reason why I need it, I just need to know if there is a leaner/cleaner way of doing this? As you can see, this only goes out to 3 but if I have 4 or 5, it won't return anything. I need it to be able to adapt to the input.

Thought I had it solved but running into an issue

 

public function get($variable){
		$variable = explode('__', $variable);
		$temp_var = '$this->settings';
		for ($i=0; $i < count($variable); $i++) { 
			$temp_var .= '[$variable['.$i.']]';
		}

		return (isset($$temp_var)) ? $$temp_var : $$temp_var;
	}

 

It outputs the following error when I try to run the function:

 

<?php
require 'loader.php';
$settings = Settings_JSON::init();
echo $settings->get('project__version');
?>

 

Notice: Undefined variable: $this->settings[$variable[0]][$variable[1]]

 

If you look above, $this->settings[$variable[0]][$variable[1]] is the variable I was using in Case 2 but now it doesn't work. What am I overlooking?

Does it work if you write:

 


$temp_var = 'this->settings';
...
$$temp_var .= '[$variable['.$i.']]';

 

I may not be understanding what you are indending to have happen.

 

Another thought is to write line 5 this way:


$temp_var .= $variable[$i];

 

 

$$temp_var .= '[$variable['.$i.']]';

 

That doesn't work. It outputs [$variable[0]] after the error I posted above.

 

$temp_var .= $variable[$i];

 

That won't work. Take a look at this string:

 

$string = 'a__b';

 

After I use __ as a delimiter in explode, I get an array like this:

 

Array
(
    [0] => a
    [1] => b
)

 

I want to use that array to access elements in this array stored in $array:

 

Array
(
    [a] => Array
        (
            [a] => This is aA
            [b] => This is aB
        )

    [b] => Array
        (
            [a] => This is bA
            [b] => This is bB
        )

)

 

This is how I am currently doing it: $array[string[0]][string[1]] and as far as I know, the only way to do this.

No problem. I actually did try that after rereading some material on variable variables. It outputs the following error:

 

Notice: Undefined variable: this->settings[$variable[0]]

 

It just baffles me. The string is being constructed with the correct variable name but still outputs the error. I know for a fact that variable exists as it works with my old method using a switch. I imagine it's has to do with how PHP is interpreting $$temp_var that I'm missing.

How about if you evauate each of those parts then as you pass them through the for()

So if var[0] = 0 and var[1] = 1 etc.

 

instead of building $tis->settings[$var[0]]...

you build $this->settings[0]...

 

 

$this->settings is an assoc array with variable key names. I'm exploding the string and using the parts as the key names. I will never know what $this->settings[0] is, it depends on what I'm loading into it. Unless I'm misinterpreting what you are saying. I may just stick with my original method as this is getting complex

So that would look like

 


public function get($variable){
		$variable = explode('__', $variable);
		$temp_var = 'this->settings';                                        // this still seems right to me
		for ($i=0; $i < count($variable); $i++) { 
			$temp_var .= '['. $variable[$i] .']';                      // changed this 
		}

		return (isset($$temp_var)) ? $$temp_var : $$temp_var;
	}

 

 

I would love to stick around and puzzle through this with you, but I need to go for a while. Good luck.

What if you try setting them array points as you iterate through and build your string

 


public function get($variable){
		$variable = explode('__', $variable);
		$temp_var = '$this->settings';                                      
		for ($i=0; $i < count($variable); $i++) { 
			$temp_var .= '['. $variable[$i] .']';       
                                $$temp_var;                                              //set the var before trying to set the next one
		}

		return (isset($$temp_var)) ? $$temp_var : $$temp_var;
	}

 

@grimmier - Didn't work, get the following error:

 

Notice: Undefined variable: $this->settings[db]
Notice: Undefined variable: $this->settings[db]

 

@Rebelrebellious - I changed it but forgot to change it back before copying and pasting it in here and I later changed it to just return $temp_var just to confirm the string is being put together correctly.

 

I thought the issue was with the variable going into isset() but it's just an issue with $$temp_var. Just having $$temp_var in the script causes the error above.


public function get($variable){
		$varArray = explode('__', $variable);
		$temp_var = '$this->settings';                                      
		foreach($varArray as $key->$value { 
			$temp_var .= '['. $value .']';       
                                                                            
		}

		return (isset($$temp_var)) ? $$temp_var : $$temp_var;
	}

I've tried using a foreach loop as well but I tried your example, even with Rebelrebellious change and I'm getting the same Notice.

 

I've tried and rewritten this over and over and it's coming out the same. I do think you were right though Rebel that it does need to be:

 

$temp_var = 'this->settings';

 

But still doesn't work. I really appreciate your guys input. If I find a solution, I'll post it

Yea, here is settings.class.php

 

<?php
abstract class Settings {
	protected $settings = array();

	protected static $instance = NULL;
	private function __clone(){}

	private function __construct(){
		$this->load_and_map('jawa');
		$this->load_and_map('project');
		$this->load_and_map('db');
	}

	static public function init(){
		if(is_null(self::$instance)){
			self::$instance = new self();
		}
		return self::$instance;
	}

	abstract function load_and_map($file);

	public function get($variable){
		$variable = explode('__', $variable);
		switch(count($variable)){
			case 1: #group
			return (isset($this->settings[$variable[0]])) ? $this->settings[$variable[0]] : false;
			break;

			case 2: #variable
			return (isset($this->settings[$variable[0]][$variable[1]])) ? $this->settings[$variable[0]][$variable[1]] : false;
			break;

			case 3: #subvariable
			return (isset($this->settings[$variable[0]][$variable[1]][$variable[2]])) ? $this->settings[$variable[0]][$variable[1]][$variable[2]] : false;
			break;
		}
	}

	public function __get($variable){
		$variable = explode('__', $variable);
		switch(count($variable)){
			case 1: #group
			return (isset($this->settings[$variable[0]])) ? $this->settings[$variable[0]] : false;
			break;

			case 2: #variable
			return (isset($this->settings[$variable[0]][$variable[1]])) ? $this->settings[$variable[0]][$variable[1]] : false;
			break;

			case 3: #subvariable
			return (isset($this->settings[$variable[0]][$variable[1]][$variable[2]])) ? $this->settings[$variable[0]][$variable[1]][$variable[2]] : false;
			break;
		}
	}

	public function get_prototype($variable){
				$varArray = explode('__', $variable);
				$temp_var = 'this->settings';                                      
				foreach($varArray as $key => $value) { 
					$temp_var .= "['$value']";
				}
				return (isset($$temp_var)) ?  "{$temp_var} worked" : "{$temp_var} doesn't work";
			}


}
?>

 

<?php
class Settings_JSON extends Settings {
	static public function init(){
		if(is_null(self::$instance)){
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function load_and_map($file){
		if(file_exists("settings/{$file}.json")){
			$handle = fopen("settings/{$file}.json", "r");
			$contents = fread($handle, filesize("settings/{$file}.json"));
			fclose($handle);
			$this->settings[$file] = json_decode($contents, TRUE);
		}else{
			return false;
		}

	}
}
?>

 

map_and_load() is what parses the json file and maps it to $obj->settings.

OK I think this should do it for yah.

 

function get($variable){
		$varArray = explode('__', $variable);
		$temp_var = 'this->settings';
	    $newArray = $$temp_var;                  
		foreach($varArray as $key=>$value) { 
			$newArray[$value] = array();      
                                            
		}
		return $newArray;
	}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.