I have the next INI file:
a.b.c = 1
a.b.d.e = 2
I am parsing this file using parse_ini_file. And it returns:
array(
'a.b.c' => 1,
'a.b.d.e' => 2
)
But I want to create a multidimensional array. My outout should be:
array(
'a' => array(
'b' => array(
'c' => 1,
'd' => array(
'e' => 2
)
)
)
)
Thank you in advance.
This is how I see it:
<?php
class ParseIniMulti {
public static function parse($filename) {
$ini_arr = parse_ini_file($filename);
if ($ini_arr === FALSE) {
return FALSE;
}
self::fix_ini_multi(&$ini_arr);
return $ini_arr;
}
private static function fix_ini_multi(&$ini_arr) {
foreach ($ini_arr AS $key => &$value) {
if (is_array($value)) {
self::fix_ini_multi($value);
}
if (strpos($key, '.') !== FALSE) {
$key_arr = explode('.', $key);
$last_key = array_pop($key_arr);
$cur_elem = &$ini_arr;
foreach ($key_arr AS $key_step) {
if (!isset($cur_elem[$key_step])) {
$cur_elem[$key_step] = array();
}
$cur_elem = &$cur_elem[$key_step];
}
$cur_elem[$last_key] = $value;
unset($ini_arr[$key]);
}
}
}
}
var_dump(ParseIniMulti::parse('test.ini'));
It's actually quite simple, you only need to change the format of the array you already have by exploding it's key:
$ini_preparsed = array(
'a.b.c' => 1,
'a.b.d.e' => 2
);
$ini = array();
foreach($ini_preparsed as $key => $value)
{
$p = &$ini;
foreach(explode('.', $key) as $k)
$p = &$p[$k];
$p = $value;
}
unset($p);
print_r($ini);
Output:
Array
(
[a] => Array
(
[b] => Array
(
[c] => 1
[d] => Array
(
[e] => 2
)
)
)
)
See as well: String with array structure to Array.
Have a look at the Zend_Config_Ini class. It does what you want, you can use it standalone (without the rest of Zend Framework) and as a bonus it supports section inheritance.
With the toArray method you can create an array from the config object.
Take a look at PHProp.
Similar to Zend_Config_Ini, but you can refer to a key in your config like ${key}
It's a my class for parsing config ini files to a multidimensional array:
class Cubique_Config {
const SEPARATOR = '.';
private static $_data = null;
public static function get() {
if (is_null(self::$_data)) {
$commonIniFile = APP . '/config' . '/common.ini';
$envIniFile = APP . '/config' . '/' . ENV . '.ini';
if (!file_exists($commonIniFile)) {
throw new Exception('\'' . $commonIniFile . '\' config file not found');
}
if (!file_exists($envIniFile)) {
throw new Exception('\'' . $envIniFile . '\' config file not found');
}
$commonIni = parse_ini_file($commonIniFile);
$envIni = parse_ini_file($envIniFile);
$mergedIni = array_merge($commonIni, $envIni);
self::$_data = array();
foreach ($mergedIni as $rowKey => $rowValue) {
$explodedRow = explode(self::SEPARATOR, $rowKey);
self::$_data = array_merge_recursive(self::$_data, self::_subArray($explodedRow, $rowValue));
}
}
return self::$_data;
}
private static function _subArray($explodedRow, $value) {
$result = null;
$explodedRow = array_values($explodedRow);
if (count($explodedRow)) {
$firstItem = $explodedRow[0];
unset($explodedRow[0]);
$result[$firstItem] = self::_subArray($explodedRow, $value);
} else {
$result = $value;
}
return $result;
}
}
Related
given a nested array of arbitrary depth like this:
$array = array(
1400=>
array(7300=>
array(
7301=> array(),
7302=> array(),
7305=> array(
7306=>array()
),
),
7314=>array()
),
);
how would one get the hierarchy of keys for any key.
for example:
getkeys(7305);
should return 1400,7300,7305 in that order
or
getkeys(7314);
should return 1400,7314
all array keys are unique values
Using RecursiveIteratorIterator
$array = array(
1400 => array(
7300 => array(
7301=> array(),
7302 => array(),
7305 => array(
7306=>array()
),
),
7314=>array()
),
);
function getKeys($key, $array) {
$found_path = [];
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($ritit as $leafValue) {
$path = array();
foreach (range(0, $ritit->getDepth()) as $depth) {
$path[] = $ritit->getSubIterator($depth)->key();
}
if (end($path) == $key) {
$found_path = $path;
break;
}
}
return $found_path;
}
print_r(getKeys(7305, $array));
// Array
// (
// [0] => 1400
// [1] => 7300
// [2] => 7305
// )
This is very interesting problem you have so I tried to make a function that will echo your keys. If this is not good enough pls let me know I can improve code. Thanks.
<?php
$a = array(
1400=>
array(7300=>
array(
7301=> array(),
7302=> array(),
7305=> array(
7306=>array()
),
),
7314=>array()
),
);
$mykey = 7306;
$level = 0;
$result = array();
$resultarray = test($a,$mykey,$level,$result);
function test($array,$mykey,$level,$result){
$level++;
foreach($array as $key => $element){
if($key == $mykey){
echo 'found';
print_r($result);
exit;
} else if(is_array($element)){
$result[$level] = $key;
$result1 = test($element,$mykey,$level,$result);
}
}
}
The idea is to check current array branch, and if the needle key isn't found, then iterate current items and check their array child nodes by recursive function calls. Before each step down we push a current key to stack, and pop the stack if the function does not found a needle key in whole branch. So if the key found, the function returns true by the chain, preserving successful keys in the stack.
function branchTraversing(& $branch, & $key_stack, $needle_key) {
$found = false;
if (!array_key_exists($needle_key, $branch)) {
reset($branch);
while (!$found && (list($key, $next_branch) = each($branch))) {
if (is_array($next_branch)) {
array_push($key_stack, $key);
$found = branchTraversing($next_branch, $key_stack, $needle_key);
if (!$found) {
array_pop($key_stack);
}
}
}
} else {
array_push($key_stack, $needle_key);
$found = true;
}
return $found;
}
function getPath(& $array, $needle_key) {
$path = [];
branchTraversing($array, $path, $needle_key);
return $path;
}
$test_keys = [1400, 7300, 7302, 7306, 7314, 666];
foreach ($test_keys as $search_key) {
echo '<p>' . $search_key . ' => [ '
. implode(', ', getPath($array, $search_key)) . ' ]</p>';
}
I have the next INI file:
a.b.c = 1
a.b.d.e = 2
I am parsing this file using parse_ini_file. And it returns:
array(
'a.b.c' => 1,
'a.b.d.e' => 2
)
But I want to create a multidimensional array. My outout should be:
array(
'a' => array(
'b' => array(
'c' => 1,
'd' => array(
'e' => 2
)
)
)
)
Thank you in advance.
This is how I see it:
<?php
class ParseIniMulti {
public static function parse($filename) {
$ini_arr = parse_ini_file($filename);
if ($ini_arr === FALSE) {
return FALSE;
}
self::fix_ini_multi(&$ini_arr);
return $ini_arr;
}
private static function fix_ini_multi(&$ini_arr) {
foreach ($ini_arr AS $key => &$value) {
if (is_array($value)) {
self::fix_ini_multi($value);
}
if (strpos($key, '.') !== FALSE) {
$key_arr = explode('.', $key);
$last_key = array_pop($key_arr);
$cur_elem = &$ini_arr;
foreach ($key_arr AS $key_step) {
if (!isset($cur_elem[$key_step])) {
$cur_elem[$key_step] = array();
}
$cur_elem = &$cur_elem[$key_step];
}
$cur_elem[$last_key] = $value;
unset($ini_arr[$key]);
}
}
}
}
var_dump(ParseIniMulti::parse('test.ini'));
It's actually quite simple, you only need to change the format of the array you already have by exploding it's key:
$ini_preparsed = array(
'a.b.c' => 1,
'a.b.d.e' => 2
);
$ini = array();
foreach($ini_preparsed as $key => $value)
{
$p = &$ini;
foreach(explode('.', $key) as $k)
$p = &$p[$k];
$p = $value;
}
unset($p);
print_r($ini);
Output:
Array
(
[a] => Array
(
[b] => Array
(
[c] => 1
[d] => Array
(
[e] => 2
)
)
)
)
See as well: String with array structure to Array.
Have a look at the Zend_Config_Ini class. It does what you want, you can use it standalone (without the rest of Zend Framework) and as a bonus it supports section inheritance.
With the toArray method you can create an array from the config object.
Take a look at PHProp.
Similar to Zend_Config_Ini, but you can refer to a key in your config like ${key}
It's a my class for parsing config ini files to a multidimensional array:
class Cubique_Config {
const SEPARATOR = '.';
private static $_data = null;
public static function get() {
if (is_null(self::$_data)) {
$commonIniFile = APP . '/config' . '/common.ini';
$envIniFile = APP . '/config' . '/' . ENV . '.ini';
if (!file_exists($commonIniFile)) {
throw new Exception('\'' . $commonIniFile . '\' config file not found');
}
if (!file_exists($envIniFile)) {
throw new Exception('\'' . $envIniFile . '\' config file not found');
}
$commonIni = parse_ini_file($commonIniFile);
$envIni = parse_ini_file($envIniFile);
$mergedIni = array_merge($commonIni, $envIni);
self::$_data = array();
foreach ($mergedIni as $rowKey => $rowValue) {
$explodedRow = explode(self::SEPARATOR, $rowKey);
self::$_data = array_merge_recursive(self::$_data, self::_subArray($explodedRow, $rowValue));
}
}
return self::$_data;
}
private static function _subArray($explodedRow, $value) {
$result = null;
$explodedRow = array_values($explodedRow);
if (count($explodedRow)) {
$firstItem = $explodedRow[0];
unset($explodedRow[0]);
$result[$firstItem] = self::_subArray($explodedRow, $value);
} else {
$result = $value;
}
return $result;
}
}
I want to dissect an array like this:
[
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
]
To a format like this:
{
"ID" : 1,
"UUID" : 1,
"pushNotifications" :
{
"sent" : 1,
"tapped" : 1
},
"campaigns" :
{
"boundDate" : 1,
"endDate" : 1,
"pushMessages" :
{
"endDate" : 1
}
}
}
It would be great if I could just set a value on an associative array in a keypath-like manner:
//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;
//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;
How to do this in PHP?
You can use :
$array = [
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
];
// Build Data
$data = array();
foreach($array as $v) {
setValue($data, $v, 1);
}
// Get Value
echo getValue($data, "campaigns.pushMessages.sentDate"); // output 1
Function Used
function setValue(array &$data, $path, $value) {
$temp = &$data;
foreach(explode(".", $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
function getValue($data, $path) {
$temp = $data;
foreach(explode(".", $path) as $ndx) {
$temp = isset($temp[$ndx]) ? $temp[$ndx] : null;
}
return $temp;
}
function keyset(&$arr, $keypath, $value = NULL)
{
$keys = explode('.', $keypath);
$current = &$arr;
while(count($keys))
{
$key = array_shift($keys);
if(!isset($current[$key]) && count($keys))
{
$current[$key] = array();
}
if(count($keys))
{
$current = &$current[$key];
}
}
$current[$key] = $value;
}
function keyget($arr, $keypath)
{
$keys = explode('.', $keypath);
$current = $arr;
foreach($keys as $key)
{
if(!isset($current[$key]))
{
return NULL;
}
$current = $current[$key];
}
return $current;
}
//Testing code:
$r = array();
header('content-type: text/plain; charset-utf8');
keyset($r, 'this.is.path', 39);
echo keyget($r, 'this.is.path');
var_dump($r);
It's a little rough, I can't guarantee it functions 100%.
Edit: At first you'd be tempted to try to use variable variables, but I've tried that in the past and it doesn't work, so you have to use functions to do it. This works with some limited tests. (And I just added a minor edit to remove an unnecessary array assignment.)
In the meanwhile, I came up with (another) solution:
private function setValueForKeyPath(&$array, $value, $keyPath)
{
$keys = explode(".", $keyPath, 2);
$firstKey = $keys[0];
$remainingKeys = (count($keys) == 2) ? $keys[1] : null;
$isLeaf = ($remainingKeys == null);
if ($isLeaf)
$array[$firstKey] = $value;
else
$this->setValueForKeyPath($array[$firstKey], $value, $remainingKeys);
}
Sorry for the "long" namings, I came from the Objective-C world. :)
So calling this on each keyPath, it actually gives me the output:
fields
Array
(
[0] => ID
[1] => UUID
[2] => pushNotifications.sent
[3] => campaigns.boundDate
[4] => campaigns.endDate
[5] => campaigns.pushMessages.endDate
[6] => pushNotifications.tapped
)
dissectedFields
Array
(
[ID] => 1
[UUID] => 1
[pushNotifications] => Array
(
[sent] => 1
[tapped] => 1
)
[campaigns] => Array
(
[boundDate] => 1
[endDate] => 1
[pushMessages] => Array
(
[endDate] => 1
)
)
)
I have a multidimensional array like this one in PHP:
Array
(
[folder1] => Array
(
[folder11] => Array
(
[0] => index.html
[1] => tester.html
)
[folder12] => Array
(
[folder21] => Array
(
[0] => astonmartindbs.jpg
)
)
)
)
and should be converted to a "file path" string like this one:
Array
(
[0] => 'folder1/folder11/index.html'
[1] => 'folder1/folder11/tester.html'
[2] => 'folder1/folder12/folder21/astonmartindbs.jpg'
)
Has anybody any ideas?
I have tried a lot any all deleted... This is the starting point of my last try:
public function processArray( $_array ) {
foreach( $_array AS $key => $value ) {
if( is_int( $key ) ) {
} else {
if( is_array( $value ) ) {
$this->processArray( $value );
} else {
}
}
}
echo $this->string;
}
But i do not come to an end.... Hope somebody can help?
A recursive function may be what you are searching for. The following function will work:
/**
* Flattens the array from the question
*
* #param array $a Array or sub array of directory tree
* #param string $prefix Path prefix of $a
*/
function flatten($a, $prefix = './') {
$paths = array();
foreach($a as $index => $item) {
// if item is a string then it is a file name (or a leaf in tree)
// prefix it and add it to paths
if(is_string($item)) {
$paths []= $prefix . $item;
} else {
// if item is a directory we call flatten on it again.
// also we append the new folder name to $prefix
foreach(flatten($item, $prefix . $index . '/') as $path) {
$paths []= $path;
}
}
}
return $paths;
}
var_dump(flatten($a));
Note that flatten() call itself inside the foreach loop with a sub array as argument. This is called a 'recursive algorithm'.
If you like the SPL you can use RecursiveArrayIterator and RecursiveIteratorIterator to iterate over a flat structure.
My result would look like this:
$arr = array(); // your array
$arr = new RecursiveArrayIterator($arr);
$iterator = new RecursiveIteratorIterator($arr, RecursiveIteratorIterator::SELF_FIRST);
$currentDepth = 0;
$currentPath = array();
$result = array();
foreach($iterator as $key => $value) {
// if depth is decreased
if ($iterator->getDepth() < $currentDepth) {
// pop out path values
do {
$currentDepth--;
array_pop($currentPath);
} while($iterator->getDepth() < $currentDepth);
}
if (is_array($value)) {
// add parent to the path
$currentPath[] = $key;
$currentDepth++;
} else {
// add children to result array
$result[] = implode('/', $currentPath).'/'.$value;
}
}
Dumping the data would then look like this:
print_r($result);
/*
Array
(
[0] => folder1/folder11/index.html
[1] => folder1/folder11/tester.html
[2] => folder1/folder12/folder21/astonmartindbs.jpg
)
*/
In your case, you need to implement, a recursive function, that you tried to do, here is a simple code, it may help you,
i am not sure if that is working or no:
$result = array();
$d = 0;
$tmp = "";
public function processArray( $_array ,$before) {
foreach( $_array AS $key => $value ) {
if( is_int( $key ) ) { // If the key is a number, then there is no a sub-array
$result[$d] = $before . '/' . $value;
$d++;
$before="";
} else {
if( is_array( $value ) ) { // if the value is an array, then we will add the key into string that we will return and search into subarray.
$before = $before . '/' . $key;
$this->processArray( $value,$before );
} else {
}
}
}
return $result;
}
Looking into Kohana documentation, i found this really usefull function that they use to get values from a multidimensional array using a dot notation, for example:
$foo = array('bar' => array('color' => 'green', 'size' => 'M'));
$value = path($foo, 'bar.color', NULL , '.');
// $value now is 'green'
Im wondering if there is a way to set the an array value in the same way:
set_value($foo, 'bar.color', 'black');
The only way i found to do that is re-building the array notation ($array['bar']['color']) and then set the value.. using eval.
Any idea to avoid eval?
function set_val(array &$arr, $path,$val)
{
$loc = &$arr;
foreach(explode('.', $path) as $step)
{
$loc = &$loc[$step];
}
return $loc = $val;
}
Sure it's possible.
The code
function set_value(&$root, $compositeKey, $value) {
$keys = explode('.', $compositeKey);
while(count($keys) > 1) {
$key = array_shift($keys);
if(!isset($root[$key])) {
$root[$key] = array();
}
$root = &$root[$key];
}
$key = reset($keys);
$root[$key] = $value;
}
How to use it
$foo = array();
set_value($foo, 'bar.color', 'black');
print_r($foo);
Outputs
Array
(
[bar] => Array
(
[color] => black
)
)
See it in action.
Look at https://gist.github.com/elfet/4713488
$dn = new DotNotation(['bar'=>['baz'=>['foo'=>true]]]);
$value = $dn->get('bar.baz.foo'); // $value == true
$dn->set('bar.baz.foo', false); // ['foo'=>false]
$dn->add('bar.baz', ['boo'=>true]); // ['foo'=>false,'boo'=>true]
That way you can set the following values more than once to the same variable.
You can make these two ways (by static variable and reference variable):
<?php
function static_dot_notation($string, $value)
{
static $return;
$token = strtok($string, '.');
$ref =& $return;
while($token !== false)
{
$ref =& $ref[$token];
$token = strtok('.');
}
$ref = $value;
return $return;
}
$test = static_dot_notation('A.1', 'A ONE');
$test = static_dot_notation('A.2', 'A TWO');
$test = static_dot_notation('B.C1', 'C ONE');
$test = static_dot_notation('B.C2', 'C TWO');
$test = static_dot_notation('B.C.D', 'D ONE');
var_export($test);
/**
array (
'A' =>
array (
1 => 'A ONE',
2 => 'A TWO',
),
'B' =>
array (
'C1' => 'C ONE',
'C2' => 'C TWO',
'C' =>
array (
'D' => 'D ONE',
),
),
*/
function reference_dot_notation($string, $value, &$array)
{
static $return;
$token = strtok($string, '.');
$ref =& $return;
while($token !== false)
{
$ref =& $ref[$token];
$token = strtok('.');
}
$ref = $value;
$array = $return;
}
reference_dot_notation('person.name', 'Wallace', $test2);
reference_dot_notation('person.lastname', 'Maxters', $test2);
var_export($test2);
/**
array (
'person' =>
array (
'name' => 'Wallace',
'lastname' => 'Maxters',
),
)
*/
I created a small class just for this!
http://github.com/projectmeta/Stingray
$stingray = new StingRay();
//To Get value
$stingray->get($array, 'this.that.someother'):
//To Set value
$stingray->get($array, 'this.that.someother', $newValue):
Updated #hair resins' answer to cater for:
When a sub-path already exists, or
When a sub-path is not an array
function set_val(array &$arr, $path,$val)
{
$loc = &$arr;
$path = explode('.', $path);
foreach($path as $step)
{
if ( ! isset($loc[$step]) OR ! is_array($loc[$step]))
$loc = &$loc[$step];
}
return $loc = $val;
}
None of the examples here worked for me, so I came up with a solution using eval() (read about the risks here, but if you don't use user data, it shouldn't be much of an issue). The if-clause in the set-method allows you to push your item onto a new or existing array at that location ($location[] = $item).
class ArrayDot {
public static function get(array &$array, string $path, string $delimiter = '.') {
return eval("return ".self::getLocationCode($array, $path, $delimiter).";");
}
public static function set(array &$array, string $path, $item, string $delimiter = '.') : void {
//if the last character is a delimiter, allow pushing onto a new or existing array
$add = substr($path, -1) == $delimiter ? '[]': '';
eval(self::getLocationCode($array, $path, $delimiter).$add." = \$item;");
}
public static function unset(array &$array, $path, string $delimiter = '.') : void {
if (is_array($path)) {
foreach($path as $part) {
self::unset($array, $part, $delimiter);
}
}
else {
eval('unset('.self::getLocationCode($array, $path, $delimiter).');');
}
}
public static function isSet(array &$array, $path, string $delimiter = '.') : bool {
if (is_array($path)) {
foreach($path as $part) {
if (!self::isSet($array, $part, $delimiter)) {
return false;
}
}
return true;
}
return eval("return isset(".self::getLocationCode($array, $path, $delimiter).");");
}
private static function getLocationCode(array &$array, string $path, string $delimiter) : string {
$path = rtrim($path, $delimiter); //Trim trailing delimiters
$escapedPathParts = array_map(function ($s) { return str_replace('\'', '\\\'', $s); }, explode($delimiter, $path));
return "\$array['".implode("']['", $escapedPathParts)."']";
}
}
Example usage:
echo '<pre>';
$array = [];
ArrayDot::set($array, 'one.two.three.', 'one.two.three.');
ArrayDot::set($array, 'one.two.three.four.', 'one.two.three.four.');
ArrayDot::set($array, 'one.two.three.four.', 'one.two.three.four. again');
ArrayDot::set($array, 'one.two.three.five.', 'one.two.three.five.');
ArrayDot::set($array, 'one.two.three.direct set', 'one.two.three.direct set');
print_r($array);
echo "\n";
echo "one.two.three.direct set: ".print_r(ArrayDot::get($array, 'one.two.three.direct set'), true)."\n";
echo "one.two.three.four: ".print_r(ArrayDot::get($array, 'one.two.three.four'), true)."\n";
Output:
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
[0] => one.two.three.
[four] => Array
(
[0] => one.two.three.four.
[1] => one.two.three.four. again
)
[five] => Array
(
[0] => one.two.three.five.
)
[direct set] => one.two.three.direct set
)
)
)
)
one.two.three.direct set: one.two.three.direct set
one.two.three.four: Array
(
[0] => one.two.three.four.
[1] => one.two.three.four. again
)