Split a string into keys of associative arrays (PHP) - php

Do you have an idea, how can a string be converted to a variable, e.g.
there is a string -> $string = 'one|two|three';
there is an array -> $arr = array('one' => array('two' => array('three' => 'WELCOME')));
I want to use all with explode(); exploded values to access the array $arr. I tried this code:
$c = explode('|', $string);
$str = 'arr[' . implode('][', $c) . ']';
echo $$str;
It doesnt work, sadly :( Any ideas?

You're doing it wrong.
You can do what you want with a loop to go through the array level by level
$string = 'one|two|three';
$arr = array('one' => array('two' => array('three' => 'WELCOME')));
$c = explode('|', $string);
$result = $arr;
foreach($c as $key)
$result = $result[$key];
echo $result; // WELCOME

Here's a sort of recursive function:
$ex_keys = array('one', 'two', 'three');
$ex_arr = array('one' => array('two' => array('three' => 'WELCOME')));
function get_recursive_var($keys, $arr) {
if (sizeof($keys) == 1)
return $arr[$keys[0]];
else {
$key = array_shift($keys);
return get_recursive_var($keys, $arr[$key]);
}
}
var_dump(get_recursive_var($ex_keys, $ex_arr));

Related

Access Array Value Using Index Variable that contains brackets [duplicate]

I have the following array:
array('data' => array('one' => 'first', 'two' => 'second'));
How i can get the value of key 'one' using string:
echo __('data.one');
function __($key) {
$parts = explode('.', $key);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
return ???;
}
Thank u!
Add your own error handling in case the key path isn't in your array, but something like:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);
This should work for you:
return $array["data"]["one"];
Also for more information and to learn a little bit see: http://php.net/manual/en/language.types.array.php
And : PHP - Accessing Multidimensional Array Values
EDIT:
This should work for you:
<?php
$str = "data.one";
$keys = explode(".", $str);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$access = $array;
foreach($keys as $v)
$access = $access[$v];
echo $access;
?>

Set multidimensional array in PHP

I have string
$s = 'controller/front/home';
value
$v = "some value";
and array
$a = [];
What is the best way to make multidimensional array like that?
$a['controller']['front']['home'] = $v;
[edit]
I don't know how many parts (separated by /) string $s can have, so manual array building by exploded parts is the last option I would consider.
I've found this after a small research:
PHP dynamic array path access
By this article, I've adapted it to following
$path = 'controller/front/home';
$value = 'some value';
$parts = explode('/', $path);
$arrayPath = [];
$temp = &$arrayPath;
foreach($parts as $part) {
if(!isset($temp[$part])) {
$temp[$part] = [];
}
$temp = &$temp[$part];
}
$temp = $value;
var_dump($arrayPath);
Prints:
array (size=1)
'controller' =>
array (size=1)
'front' =>
array (size=1)
'home' => string 'some value' (length=10)
$a = $v; foreach (array_reverse(explode('/', $s)) as $i) $a = array($i => $a);
You can do it like this
$array = explode('/', $s);
and then :
$a[$array[0]][$array[1]][$array[2]] = $v;

get value from array using string php

I have the following array:
array('data' => array('one' => 'first', 'two' => 'second'));
How i can get the value of key 'one' using string:
echo __('data.one');
function __($key) {
$parts = explode('.', $key);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
return ???;
}
Thank u!
Add your own error handling in case the key path isn't in your array, but something like:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);
This should work for you:
return $array["data"]["one"];
Also for more information and to learn a little bit see: http://php.net/manual/en/language.types.array.php
And : PHP - Accessing Multidimensional Array Values
EDIT:
This should work for you:
<?php
$str = "data.one";
$keys = explode(".", $str);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$access = $array;
foreach($keys as $v)
$access = $access[$v];
echo $access;
?>

how to get associative array from string

I have one string like:-
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
Now, I want to get it in following associative array format:-
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
Note:- These all values are separated by space only. Any help will be appreciable.
Thanks in advance
$final_array = array();
$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
list($k, $v) = explode('=', $kvp);
$final_array[$k] = $v;
}
I can suggest you to do it with a regular expression:
$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all( '/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches );
$res = array_combine( $matches['key'], $matches['val'] );
working example in phpfiddle
$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
EXPLODE
this code will solve your problem.
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode ( ' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
out put of this code is
Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )
I think you have to split this string two times
divide with space
divide with '='

How to set a deep array in PHP

Assume I have the following function
function setArray(&$array, $key, $value)
{
$array[$key] = $value;
}
In the above function, key is only at the first level, what if I want to set the key at the 2nd or 3rd levels, how to rewrite the function?
e.g.
$array['foo']['bar'] = 'test';
I want to use the same function to set the array value
This one should work. Using this function you can set any array element in any depth by passing a single string containing the keys separated by .
function setArray(&$array, $keys, $value) {
$keys = explode(".", $keys);
$current = &$array;
foreach($keys as $key) {
$current = &$current[$key];
}
$current = $value;
}
You can use this as follows:
$array = Array();
setArray($array, "key", Array('value' => 2));
setArray($array, "key.test.value", 3);
print_r($array);
output:
Array (
[key] => Array
(
[value] => 2
[test] => Array
(
[value] => 3
)
)
)
You can use array_merge_recursive
$array = array("A" => "B");
$new['foo']['bar'] = 'test';
setArray($array, $new);
var_dump($array);
Output
array (size=2)
'A' => string 'B' (length=1)
'foo' =>
array (size=1)
'bar' => string 'test' (length=4)
Function Used
function setArray(&$array, $value) {
$array = array_merge_recursive($array, $value);
}
this function should do it, the key should be an array, for example array('foo', 'bar')
function setArray(&$array, array $keys, $value) {
foreach($keys as $key) {
if(!isset($array[$key])) {
$array[$key] = array();
}
$array = &$array[$key];
}
$array = $value;
}
$arr = array();
setArray($arr, array('first', 'second'), 1);
var_dump($arr);
// dumps array(1) { ["first"]=> array(1) { ["second"]=> int(1) } }
Tested and works.
Use array_replace_recursive instead of array_merge_recursive as it handles same-key scenario correctly. See this https://3v4l.org/2ICmo
Just like this:
function setArray(&$array, $key1, $key2, $value)
{
$array[$key1][$key2] = $value;
}
But why you want to use function? Using it like this:
setArray($array, 'foo', 'bar', 'test');
takes more time to write something like this:
$array[1][2] = 'test';

Categories