I want create a nested array from a config file dynamically.
My config file structure is like this:
parameter1 value1;
parameter2 value2;
parameter3 value3;
block1{
parameter1-1 value1-1;
parameter1-2 value1-2;
block1-1{
parameter1-1-1 value1-1-1;
parameter1-1-2 value1-1-2;
block1-1-1{
parameter1-1-1-1 value1-1-1-1;
parameter1-1-1-2 value1-1-1-2;
}
block1-1-2{
parameter1-1-2-1 value1-1-2-1;
parameter1-1-2-2 value1-1-2-2;
}
}
block1-2{
parameter1-2-1 value1-2-1;
parameter1-2-2 value1-2-2;
block1-2-1{
parameter1-2-1-1 value1-2-1-1;
parameter1-2-1-2 value1-2-1-2;
}
block1-2-2{
parameter1-2-2-1 value1-2-2-1;
parameter1-2-2-2 value1-2-2-2;
}
}
}
block2{
parameter2-1 value2-1;
parameter2-2 value2-2;
block2-1{
parameter2-1-1 value2-1-1;
parameter2-1-2 value2-1-2;
block2-1-1{
parameter2-1-1-1 value2-1-1-1;
parameter2-1-1-2 value2-1-1-2;
}
block2-1-2{
parameter2-1-2-1 value2-1-2-1;
parameter2-1-2-2 value2-1-2-2;
}
}
block2-2{
parameter2-2-1 value2-2-1;
parameter2-2-2 value2-2-2;
block2-2-1{
parameter2-2-1-1 value2-2-1-1;
parameter2-2-1-2 value2-2-1-2;
}
block2-2-2{
parameter2-2-2-1 value2-2-2-1;
parameter2-2-2-2 value2-2-2-2;
}
}
}
and i want this array dynamically in php:
$blocks = array(
$parameter => $value,
$parameter => $value,
$block => array(
$parameter => $value,
$parameter => $value,
$block => array(
$parameter => $value,
$parameter => $value,
$block => array(
$parameter => $value,
$parameter => $value
...
)
)
)
);
How to create dynamically nested array in PHP
Thanks.
UPDATE:
I read file line by line to an array and i want create above structure for edit it and write it again to config file.
I means from "dynamic" is creating array inside "for" or other similar things.
Try this... (change "conf.txt" to "your conf file name")
<?php
$file = fopen("conf.txt","r");
$array = array();
$a = createArray($file, $array);
fclose($file);
print("<pre>".print_r($a,true)."</pre>");
function createArray($file, $array){
while(! feof($file)){
$line = fgets($file);
$line = trim($line);
if ($line == ""){
continue;
}
if (strpos($line,'{') !== false){
$line = trim(str_replace('{','',$line));
$array[$line] = array();
$array[$line] = createArray($file, $array[$line]);
} else if (strpos($line,'}') !== false) {
return $array;
} else {
$line = str_replace(';','',$line);
$key = strtok($line, ' ');
$value = strtok(' ');
$array[$key] = $value;
}
}
return $array;
}
?>
Creating array dynamically:
in all PHP versions:
$foo = array();
in PHP 5.4+ (aka "short syntax"):
$foo = [];
Creating nested array dynamically:
$foo = [];
$foo['bar'] = [];
$foo['bar']['zoo'] = [];
or
$foo = [];
$bar = ['zoo' => []];
$foo['bar'] = $bar;
And finally call
print_r($foo);
to see what you got created. Both cases are equal so you will see:
Array
(
[bar] => Array
(
[zoo] => Array
(
)
)
}
Please see docs on array: http://php.net/manua/en/language.types.array.php
Related
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);
Suppose, i have the fallowing json:
{
"foo.bar": 1
}
and i want to save this like this:
$array["foo"]["bar"] = 1
but i also can have more than 2 "parameters" in string. For example:
{
"foo.bar.another_foo.another_bar": 1
}
and i want to save this same way.
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
Any ideas how can i do that in case that i don't know how many parameters i have?
This is far from the nicest solution, but I've been programming all day so I'm a little tired, but I hope it gives you something to work off, or at least a working solution for the time being.
Here's the IDEone of it working: click
And here's the code:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
Output:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
Wasn't sure whether your JSON string could have multiples or not so I made it handle the former.
Hope it helps, may come back and clean it up a bit in the future.
Start with a json_decode
Then build a foreach loop to break apart the keys and pass them to some kind of recursive function that creates the values.
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
Then write your recursive function:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
I have not tested this code so don't expect to just cut and past but the strategy should work. Notice that $new_stuff is passed by reference to the recursive function. This is very important.
Try the following trick for "reformatting" into json string which will fit the expected array structure:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1
I am trying to get my head around arrays.
The arrays should look like this:
$questions[$a] => array( [0] => No, comment1
[1] => Yes, comment2
[2] => No, comment3 )
$answer[$a] => array( [0] => No
[1] => Yes
[3] => No )
$comment[$a] => array( [0] => comment1
[1] => comment2
[3] => comment3 )
=========================================================================
SECOND EDIT: Need to execute this in the loop to create a third array -
if($answer[$a] == "Yes") { $display[$a] = "style='display:none'";
} else { $display[$a] = "style='display:block'"; }
This is what i have: (28th for minitech)
while ($a > $count)
{
if($count > 11) {
foreach($questions as $q) {
list($answer, $comments[]) = explode(',', $q);
if($answer === "Yes") {
$display[$a] = "style='display:none'";
} else {
$display[$a] = "style='display:block'";
}
$answers[] = $answer;
}
}
$a++;
}
If they are actually strings, explode works:
$answers = array();
$comments = array();
$display = array();
foreach(array_slice($questions, 11) as $question) {
list($answer, $comments[]) = explode(',', $question);
$display[] = $answer === 'Yes' ? 'style="display: none"' : 'style="display: block"';
$answers[] = $answer;
}
Here’s a demo!
Change your while loop to this
while ...
{
$parts = explode(',', $questions[$a]);
$answer[$a][] = trim($parts[0]);
$comment[$a][] = trim($parts[1]);
}
In your original code you were overwriting the $answer[$a] and $comment[$a] each time, not appending to the end of an array
$questions[$a] = array('Q1?' => 'A1', 'Q2?' => 'A2', 'Q3?' => 'A3');
foreach($questions[$a] as $key => $value)
{
$comment[$a][] = $key;
$answer[$a][] = $value;
}
This should work.
foreach ($questions[$a] as $key=>$value){
$temp = explode(',',$value);
$answer[$key] = $temp[0];
$comment[$key] = $temp[1];
}
$key will have 0,1,2 respectively. $value will have the values for each $question[$a](No,Comment1 ....)
Can't think of a funky one-liner, but this should do it:
foreach ($questions as $a => $entries) {
foreach ($entries as $k => $entry) {
$parts = array_map('trim', explode(',', $entry));
$answer[$a][$k] = $parts[0];
$comment[$a][$k] = $parts[1];
}
}
$questions = array( 0 => 'No,comment1',1 => 'Yes,comment2',2 => 'No,comment3' );
foreach($questions as $question)
{
$parts = explode(",",$question);
$answer[] = $parts[0];
$comment[] = $parts[1];
}
echo "<pre>";
print_r($answer);
print_r($comment);
Here is the right answer
foreach($questions as $key => $question){
foreach($question as $q => $data){
$data= explode(',',$data);
$comments[$key][$q] = $data[0];
$answer[$key][$q] = $data[1];
}
}
If the values in $questions are comma-separated strings you could use an array_walk function to populate your $answer and $comment arrays
$question = array(...); //array storing values as described
$answer = array();
$comment = array();
array_walk($question, function ($value, $key) use ($answer,$comment) {
$value_array = explode(',', $value);
$answer[$key] = $value_array[0];
$comment[$key] = $value_array[1];
});
Note that this is shown using an anonymous function (closure) which requires PHP >= 5.3.0. If you had a lower version of PHP, you would need to declare a named function, and declare $answer and $comment as globals in the function. I think this is a hacky approach (using globals like this) so if I was using PHP < 5.3 I would probably just use a foreach loop like other answers to your question propose.
Functions like array_walk, array_filter and similar functions where callbacks are used are often great places to leverage the flexibility provided by anonymous functions.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Dynamic array keys
I have an array $Values
which is set up like this
$Values
1
2
3
a
b
c
4
which is nested.
and I have a key like this: $key = "a"]["b"]["c";
Can I now do: Values[$key], ti get the value in c ?
#Edit
Simply said: I want to get the value from array $Values["a"]["b"]["c"] By doing $Values[$key]. What should my key be then?
No, but you can extract the result:
$Values = array( '1' => 'ONE',
'2' => 'TWO',
'3' => 'THREE',
'a' => array( 'b' => array( 'c' => 'alphabet') ),
'4' => 'FOUR'
);
$key = '"a"]["b"]["c"';
$nestedKey = explode('][',$key);
$searchArray = $Values;
foreach($nestedKey as $nestedKeyValue) {
$searchArray = $searchArray[trim($nestedKeyValue,'"')];
}
var_dump($searchArray);
Will only work if $key is valid.
Now how do you get in a situation with a key like this anyway? Perhaps if you explained the real problem, we could give you a real answer rather than a hack.
No, you only can get individual keys from variables. Depending on what you really want to do you could use references to your array elements.
Nah you can't. This is invalid syntax.
Hover you can do:
$key = 'a,b,c';
// or:
$key = serialize( array( 'a','b', 'c'));
// or many other things
And than implement your array-like class which will implement ArrayAccess or ArrayObject (let's way you'll stick with $key = 'a,b,c';):
class MyArray extends ArrayAccess {
protected $data = array();
protected &_qetViaKey( $key, &$exists, $createOnNonExisting = false){
// Parse keys
$keys = array();
if( strpos( $key, ',') === false){
$keys[] = $key;
} else {
$keys = explode( ',', $key);
}
// Prepare variables
static $null = null;
$null = null;
$exists = true;
// Browse them
$progress = &$this->data;
foreach( $keys as $key){
if( is_array( $progress)){
if( isset( $progress[ $key])){
$progress = $progress[ $key];
} else {
if( $createOnNonExisting){
$progress[ $key] = array();
$progress = $progress[ $key];
} else {
$exists = false;
break;
}
}
} else {
throw new Exception( '$item[a,b] was already set to scalar');
}
}
if( $exists){
return $progress;
}
return $null;
}
public offsetExists( $key){
$exists = false;
$this->_getViaKey( $key, $exists, false);
return $exists;
}
// See that we aren't using reference anymore in return
public offsetGet( $key){
$exists = false;
$value = $this->_getViaKey( $key, $exists, false);
if( !$exists){
trigger_error( ... NOTICE ...);
}
return $value;
}
public offsetSet ( $key, $val){
$exists = false;
$value = $this->_getViaKey( $key, $exists, true);
$value = $val;
}
}
// And use it as:
$array = MyArray();
$array['a']['b']['c'] = 3;
$array['a,b,c'] = 3;
Or implement function:
public function &getArrayAtKey( $array, $key){
// Similar to _qetViaKey
// Implement your own non existing key handling
}
I have an array in the same level.
$original = Array(
0=>"03ssss",//substr("03ssss",0,2)="03" => parent index
1=>"04aaaa",
2=>"05absd",
3=>"07sdsa",
4=>"08sdsd",
5=>"03tttt", //substr("03tttt",0,2)="03" => parent index
6=>"04xxxx, //substr("03xxxx",0,2)="04" => child index
7=>"05sdds",
8=>"07sdfd",
9=>"08sdff",
10=>"04xsax", //substr("03xxxx",0,2)="04" => child index
11=>"05sdfs",
12=>"07sdfds",
13=>"08asap",
)
How Can create from $original to multiple array something like this?
$move_level = Array(
0=>array(0=>"04aaaa 05absd 07sdsa 08sdsd"),
1=>array(0=>"04xxxx 05sdds 07sdfd 08sdff",
1=>"04xsax 05sdfs 07sdfds 08asap")
);
thanks
This splits the $original array into sub arrays at each element starting with '03':
$move_level = array();
$ary = array();
foreach($original as $value) {
if (strpos($value, '03') === 0) {
$move_level[] = $ary;
$ary = array();
} else {
$ary[] = $value;
}
}
$move_level[] = $ary;