How can I define dynamically the associative array keys? - php

I have two variable:
$keystr = 'plant,fruit,exotic';
$value='kiwi';
how can i create the associative array?
$arr = ('plant'=>array('fruit'=>array('exotic'=>'kivi')));

$keystr = 'plant,fruit,exotic';
$value='kiwi';
$arr = array();
$current = &$arr;
$keys = explode(',', $keystr);
foreach($keys as $key) {
$current[$key] = array();
$current = &$current[$key];
}
$current = $value;
unset($current);
var_dump($arr);
See http://ideone.com/YiMIRb for a demonstration

Related

How to group same array values in PHP?

I want to group in subarray the identical values ​​while preserving the original order of each group of values.
I want this :
array('a','b','b','c','c','c','a','a');
to become :
array( array('a'),array('b','b'),array('c','c','c'),array('a','a'));
$source = array('a','b','b','c','c','c','a','a');
$tempvalue = false;
$temparr = array();
$new = array();
foreach ($source as $value) {
if ($tempvalue && $value != $tempvalue){
$new[] = $temparr;
$temparr = array();
}
$temparr[] = $value;
$tempvalue = $value;
}
$new[] = $temparr;
echo json_encode($new);
output:
[["a"],["b","b"],["c","c","c"],["a","a"]]

How to divide an array to two dimensional array in PHP

I have an array like below.
$arr=array('0_1','0_3','1_2',1_1','4_1');
can i divide it into
$arr[0][1]='0_1';
$arr[0][3]='0_3';
...
Thanks.
$newArray = [];
foreach ($arr as $item) {
$items = explode('_', $item);
$newArray[$items[0]][$items[1]] = $item;
}
var_dump($newArray);
exit();
This should do the trick. You should have a look at the explode function
Another way to do this without foreach loop. :->
$arr = array('0_1','0_3','1_2','1_1','4_1');
$result = [];
array_walk($arr,function($v,$k)use (&$result){
$data = explode("_",$v);
$result[$data[0]][$data[1]] = $v;
});
print_r($result);
$arrv = array('0_1','0_3','1_2','1_1','4_1');
$newArray = [];
array_walk($arrv,function($value,$key){
global $newArray;
$indexArray = explode("_",$value);
$newArray[$indexArray[0]][$indexArray[1]] = $value;
});
var_dump($newArray);

String to associative array

I'm having trouble using preg_match_all to split a string into key value pairs. An example of my string:
"%Title:Movie%Sortable%Writer:%Indexed:false%"
Where I expect results like:
$result['Title'] = 'Movie';
$result['Sortable'] = '';
$result['Writer'] = '';
$result['Indexed'] = 'false';
I can split the string using preg_match('/%/',$str,-1,PREG_SPLIT_NO_EMPTY); but it returns an indexed array. I need an associative array so that order is not important and I can use the key in a switch statement. What would be the correct regex to use in preg_match_all?
Try with:
$input = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$output = array();
$data = explode('%', $input);
foreach ($data as $item) {
list($key, $value) = explode(':', $item);
$output[$key] = $value;
}
<?php
$arr = array();
$string = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$d = explode('%', $string);
foreach($d as $item){
list($key,$value) = explode(':', $item);
$arr[$key] = $value;
}
print_r($arr);
?>

PHP set dynamic array index

I have the following key/value from my $_POST variable:
Array
(
'translations_0_comment' => 'Greetings from UK'
)
What I would like is to set this values to the following array
$data[translations][0][comment] = 'Greetings from UK';
So the idea is that I can have anything in my KEY values, and from that I will populate an array.
Is there any safe way to do this without using eval() ?
All help is appreciated.
UPDATE:
this would be the idea with eval()
foreach ($_POST as $key => $dataValue) {
$a = explode("_", $key);
$builder = '$object';
foreach ($a as $value) {
$builder.='['.$value.']';
}
$builder.=' = '.$dataValue.';';
eval($builder);
}
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
explode() is what you need:
$data = array();
foreach ($postData as $key => $val) {
$explodedKey = explode('_', $key);
$data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}
No need to use eval().
I think this is what you are looking for
Example
In your form which generate the $_POST data rename the input attribute as follows
<input name="data[translations][0][comment]" />
and now your $_POST['data'] will be an array
$data = array();
foreach ($_POST as $keys => $val) {
$keys_list = explode('_', $keys);
$link = &$data;
foreach ($keys_list as $key) {
$link[$key] = $val;
$link = &$link[$key];
}
}
Try this one sir.
$array = array
(
'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);
$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);
$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
$start .= "array(\"".$array1[$i]."\" => ";
$end .=")";
}
$start = $start ."\"".$arrValue[0]."\"".$end;
eval("\$arr = $start;");
print_r($arr);

Create dynamic multidimensional array

I'm trying to create an array while parsing a string separated with dots
$string = "foo.bar.baz";
$value = 5
to
$arr['foo']['bar']['baz'] = 5;
I parsed the keys with
$keys = explode(".",$string);
How could I do this?
You can do:
$keys = explode(".",$string);
$last = array_pop($keys);
$array = array();
$current = &$array;
foreach($keys as $key) {
$current[$key] = array();
$current = &$current[$key];
}
$current[$last] = $value;
DEMO
You can easily make a function out if this, passing the string and the value as parameter and returning the array.
You can try following solution:
function arrayByString($path, $value) {
$keys = array_reverse(explode(".",$path));
foreach ( $keys as $key ) {
$value = array($key => $value);
}
return $value;
}
$result = arrayByString("foo.bar.baz", 5);
/*
array(1) {
["foo"]=>
array(1) {
["bar"]=>
array(1) {
["baz"]=>
int(5)
}
}
}
*/
This is somehow related to the question you can find an answer to, here:
PHP One level deeper in array each loop made
You would just have to change the code a little bit:
$a = explode('.', "foo.bar.baz");
$b = array();
$c =& $b;
foreach ($a as $k) {
$c[$k] = array();
$c =& $c[$k];
}
$c = 5;
print_r($b);

Categories