convert tab/space delimited lines into nested array - php

I would like convert the below text into a nested array, something like you would get with MPTT database structure.
I am getting the data from a shell script and need to display it on a website. Don't have any control over the format :/
There is lots of information about array -> list, but not much going the other way.
Any input would be appreciated, thanks.
cat, true cat
=> domestic cat, house cat, Felis domesticus, Felis catus
=> kitty, kitty-cat, puss
=> mouser
=> alley cat
=> tom, tomcat
=> gib
=> Angora, Angora cat
=> Siamese cat, Siamese
=> blue point Siamese
=> wildcat
=> sand cat
=> European wildcat, catamountain, Felis silvestris
=> cougar, puma, catamount, mountain lion, painter, panther, Felis concolor
=> ocelot, panther cat, Felis pardalis
=> manul, Pallas's cat, Felis manul
=> lynx, catamount
=> common lynx, Lynx lynx
=> Canada lynx, Lynx canadensis

You have got a sorted tree list here already. Each next line is either a child of the previous line or a sibling. So you can process over the list, get the name of an item, gain the level an item is in by it's indentation and create an element out of it.
1 Line <=> 1 Element (level, name)
So every element has a name and zero or more children. From the input it can also be said which level it belongs to.
An element can be represented as an array, in which it's first value is the name and the second value is an array for the children.
As the list is sorted, we can use a simple map, which per level is an alias to the children of a certain level. So with the level each element has, we can add it to the stack:
$self = array($element, array());
$stack[$level][] = &$self;
$stack[$level + 1] = &$self[1];
As this code-example shows, the stack/map for the current level is getting $self as children added:
$stack[$level][] = &$self;
The stack for the level one higher, get's the reference to the children of $self (index 1):
$stack[$level + 1] = &$self[1];
So now per each line, we need to find the level. As this stack shows, the level is sequentially numbered: 0, 1, 2, ... but in the input it's just a number of spaces.
A little helper object can do the work to collect/group the number of characters in a string to levels, taking care that - if a level yet does not exist for an indentation - it is added, but only if higher.
This solves the problem that in your input there is no 1:1 relation between the size of the indentation and it's index. At least not an obvious one.
This helper object is exemplary named Levels and implements __invoke to provide the level for an indent while transparently adding a new level if necessary:
$levels = new Levels();
echo $levels(''); # 0
echo $levels(' '); # 1
echo $levels(' '); # 1
echo $levels(' '); # 2
echo $levels(' '); # Throws Exception, this is smaller than the highest one
So now we can turn indentation into the level. That level allows us to run the stack. The stack allows to build the tree. Fine.
The line by line parsing can be easily done with a regular expression. As I'm lazy, I just use preg_match_all and return - per line - the indentation and the name. Because I want to have more comfort, I wrap it into a function that does always return me an array, so I can use it in an iterator:
$matches = function($string, $pattern)
{
return preg_match_all($pattern, $string, $matches, PREG_SET_ORDER)
? $matches : array();
};
Using on input with a pattern like
/^(?:(\s*)=> )?(.*)$/m
will give me an array per each line, that is:
array(whole_line, indent, name)
You see the pattern here? It's close to
1 Line <=> 1 Element (level, name)
With help of the Levels object, this can be mapped, so just a call of a mapping function:
function (array $match) use ($levels) {
list(, $indent, $name) = $match;
$level = $levels($indent);
return array($level, $name);
};
From array(line, indent, name) to array(level, name). To have this accessible, this is returned by another function where the Levels can be injected:
$map = function(Levels $levels) {
return function ...
};
$map = $map(new Levels());
So, everything is in order to read from all lines. However, this needs to be placed into the the tree. Remembering adding to the stack:
function($level, $element) use (&$stack) {
$self = array($element, array());
$stack[$level][] = &$self;
$stack[$level + 1] = &$self[1];
};
($element is the name here). This actually needs the stack and the stack is actually the tree. So let's create another function that returns this function and allow to push each line onto the stack to build the tree:
$tree = array();
$stack = function(array &$tree) {
$stack[] = &$tree;
return function($level, $element) use (&$stack) {
$self = array($element, array());
$stack[$level][] = &$self;
$stack[$level + 1] = &$self[1];
};
};
$push = $stack($tree);
So the last thing to do is just to process one element after the other:
foreach ($matches($input, '/^(?:(\s*)=> )?(.*)$/m') as $match) {
list($level, $element) = $map($match);
$push($level, $element);
}
So now with the $input given this creates an array, with only (root) child nodes on it's first level and then having an array with two entries per each node:
array(name, children)
Name is a string here, children an array. So this has already done the list to array / tree here technically. But it's rather burdensome, because you want to be able to output the tree structure as well. You can do so by doing recursive function calls, or by implementing a recursive iterator.
Let me give an Recursive Iterator Example:
class TreeIterator extends ArrayIterator implements RecursiveIterator
{
private $current;
public function __construct($node)
{
parent::__construct($node);
}
public function current()
{
$this->current = parent::current();
return $this->current[0];
}
public function hasChildren()
{
return !empty($this->current[1]);
}
public function getChildren()
{
return new self($this->current[1]);
}
}
This is just an array iterator (as all nodes are an array, as well as all child nodes) and for the current node, it returns the name. If asked for children, it checks if there are some and offers them again as a TreeIterator. That makes using it simple, e.g. outputting as text:
$treeIterator = new RecursiveTreeIterator(
new TreeIterator($tree));
foreach ($treeIterator as $val) echo $val, "\n";
Output:
\-cat, true cat
|-domestic cat, house cat, Felis domesticus, Felis catus
| |-kitty, kitty-cat, puss
| |-mouser
| |-alley cat
| |-tom, tomcat
| | \-gib
| |-Angora, Angora cat
| \-Siamese cat, Siamese
| \-blue point Siamese
\-wildcat
|-sand cat
|-European wildcat, catamountain, Felis silvestris
|-cougar, puma, catamount, mountain lion, painter, panther, Felis concolor
|-ocelot, panther cat, Felis pardalis
|-manul, Pallas's cat, Felis manul
\-lynx, catamount
|-common lynx, Lynx lynx
\-Canada lynx, Lynx canadensis
If you're looking for more HTML output control in conjunction with an recursive iterator, please see the following question that has an example for <ul><li> based HTML output:
How can I convert a series of parent-child relationships into a hierarchical tree? (Should as well have some other insightful information for you)
So how does this look like all together? The code to review at once as a gist on github.

In contrast to my previous answer that is quite a bit long and explains all the steps, it's also possible to do the same but more compressed.
The line splitting can be done with strtok
The preg_match then "on" the line making mapping more immanent
The Levels can be compressed into an array taken for granted that the input is correct.
This time for the output, it's a recursive function not iterator that spills out a nested <ul> list. Example code (Demo):
// build tree
$tree = $levels = array();
$stack[1] = &$tree;
for ($line = strtok($input, $token = "\n"); $line; $line = strtok($token)) {
if (!preg_match('/^(?:(\s*)=> )?(.*)$/', $line, $self)) {
continue;
}
array_shift($self);
$indent = array_shift($self);
$level = #$levels[$indent] ? : $levels[$indent] = count($levels) + 1;
$stack[$level][] = &$self;
$stack[$level + 1] = &$self[];
unset($self);
}
unset($stack);
// output
tree_print($tree);
function tree_print(array $tree, $in = '') {
echo "$in<ul>\n";
$i = $in . ' ';
foreach ($tree as $n)
printf("</li>\n", printf("$i<li>$n[0]") && $n[1] && printf($i, printf("\n") & tree_print($n[1], "$i ")));
echo "$in</ul>\n";
}
Edit: The following goes even one step further to completely drop the tree array and do the output directly. This is a bit mad because it mixes the reordering of the data and the output, which tights things together so not easy to change. Also the previous example already looks cryptic, this is beyond good and evil (Demo):
echo_list($input);
function echo_list($string) {
foreach ($m = array_map(function($v) use (&$l) {
return array(#$l[$i = &$v[1]] ? : $l[$i] = count($l) + 1, $v[2]);
}, preg_match_all('/^(?:(\s*)=> )?(.*)$/m', $string, $m, PREG_SET_ORDER) ? $m : array()) as $i => $v) {
$pi = str_repeat(" ", $pl = #$m[$i - 1][0]); # prev
$ni = str_repeat(" ", $nl = #$m[$i + 1][0]); # next
(($v[0] - $pl) > 0) && printf("$pi<ul>\n"); # is child of prev
echo ' ' . str_repeat(" ", $v[0] - 1), "<li>$v[1]"; # output self
if (!$close = (($nl - $v[0]) * -1)) echo "</li>\n"; # has sibling
else if ($close < 0) echo "\n"; # has children
else for (printf("</li>\n$ni" . str_repeat(" ", $close - 1) . "</ul>\n"); --$close;) # is last child
echo $ni, $nn = str_repeat(" ", $close - 1), " </li>\n",
$ni, $nn, "</ul>\n";
}
}
This drops strtok again and goes back to the idea to use preg_match_all. Also it stores all lines parsed, so that it's possible to look behind and ahead to determine how many <ul> elements need to be opened or closed around the current element.

Related

PHP recursive foreach with left, right and depth

I have a json file taken from geonames.org and I want to add the data from that file using php recursive foreach.
I only succeeded that I just did not understand the concept of left right depth. Depth is saved correctly.
My code is:
public function buildTree($elements, $count = 1, $depth = 0)
{
if (isset($elements->geonames)) {
foreach ($elements->geonames as $element) {
$left = $count++;
$elementDB = new \App\Geo();
$elementDB->id = $element->geonameId;
$elementDB->parent_id = NULL;
$elementDB->left = $left;
$elementDB->right = $right;
$elementDB->depth = $depth;
$elementDB->name = $element->name;
$elementDB->country = $element->countryCode;
$elementDB->level = $element->fcode;
$elementDB->lat = $element->lat;
$elementDB->long = $element->lng;
$elementDB->save();
$elements = $this->getList($element->geonameId, 'element');
if ($depth < 1) {
$this->buildTree($elements, $count, $depth + 1);
}
$right = $count++;
echo "Added element " . $element->name . "\n";
}
}
}
This should happen
It seems you want to understand how it works?
You use recursion to process every element. Variable $elements is a tree (or sub-tree) with nodes. Your code has to look through your tree from left to right. On every iteration you check if $elements has nodes. If $elements has (it might be ordered array or struct with fields) nodes you have to process those nodes. During every checking you detect every node if they have other children nodes or not. When you find the first (let's name it "A") node that has other children nodes you have to go into on next iteration recursion to process children nodes of current child node ("A").
The numbers represent the order in which the nodes are accessed in Left-Right depth algorithm.
Frankly speaking I don't understand for what you have added:
$this->buildTree($elements, $count, $depth + 1);
And it's a bad style reassignment for variable in foreach:
May be it will be interesting for you When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?
I'm assuming here you're making a binary search tree. Basically, a tree is a graph with a root, "regular" nodes, and leaves.
There's always one single root, at the top, which is a particular node.
Leaves don't have other nodes below, they are the "ends" of the tree.
Regular nodes have possibly two children, one smaller (on the left) and one bigger (on the right). This makes something like that:
As you can see, all nodes coming from the left child of the root are smaller than 8. All children on the right are bigger than 8. This way, when you search for "10", you immediatly know that you have to go through the right child of the root, no need the explore left side (that means less processing time).
A possible binary search tree search algorithm implementation is as follows:
function buildTree($elements, $left, $right, $needle){
if ($left > $right) return null;
$middle = floor(($left + $right) / 2);
$val = $elements[$middle];
if ($val === $needle) return $val;
else if ($val < $needle) return buildTree($elements, $left + 1, $right, $needle);
else if ($val > $needle) return buildTree($elements, $left, $right + 1, $needle);
}
echo buildTree([1, 2, 3, 4, 5], 0, 5, 4);
You just need to adapt this to your problem

Algorithm to find amount of levels in an array of arrays

I'm working on an algorithm to calculate the amount of levels in an array of arrays.
The reason I need this is because I need to fetch a list of categories from the database that belongs to a category parent, and depending of the amount of levels this array has, I need to display an amount of category lists (to select categories).
So it would be a category list for each level of categories, for example
Vehicles
Cars
honda
Red
Blue
Yellow
ford
Red
suzuki
Red
Green
BMW
Motorcycles
bla bla
bla bla
Groceries
Fruits
Berries
Red
Strawberries
So I need a function to check the amount of levels of the selected parent, for example if i pass the ID of vehicles i want it to return 4 or 3 if we count Vehicles as level 0, so I know that if the client selected Vechicles from the first list I will have to display 3 more lists.
So far, what I have that is not working is
function count_children_level($list_of_children, $start_depth = 0){
// if the data being passed is an array
if(is_array($list_of_children)){
// amount of nodes is equal to the
$max = $start_depth;
foreach($list_of_children as $i){
$result = count_children_level($i, $start_depth + 1);
if ($result > $max){
$max = $result;
}
}
return $max;
}
//if is not array
else {
return $start_depth;
}
}
I really need to understand how this works because i have to work with several functions like this one, so please if you can, explain your answer in detail.
Thanks
The depth of a nested array is equal to the depth of the largest array in it + 1.
So for your recursive function, instead of passing the entire array every time, you can make an actual recursive call that only gets the depth of the sub-array. So this function returns 1 for a normal, flat array and 1 extra for each level.
<?php
function array_depth($array) {
// Determine largest sub-array. Start with 0 if there are no arrays at all.
$max = 0;
foreach ($array as $item) {
if (is_array($item)) {
// Make the recursive call, passing not $array, but the sub-array ($item)
// to the function again.
$depth = array_depth($item);
if ($depth > $max)
$max = $depth;
}
}
// Depth of this array is the depth of the largest sub-array + 1.
return $max + 1;
}
I called it like this:
echo array_depth(
array('x' =>
array('y' =>
array('z')))); // Returns 3.
My interpretation of what #GolezTrol said in their answer ("The depth of a nested array is equal to the depth of the largest array in it + 1"):
function array_depth($a)
{
// If $a is not an array or it's an empty array then its depth is 1
if (! is_array($a) || count($a) == 0) {
return 0;
}
// Otherwise, add 1 to the maximum depth of the elements it contains
return 1 + max(array_map('array_depth', $a));
}
Another solution with the RecursiveIteratorIterator class. In this way you don't need a recursive function:
$array = array(
'Vehicles' => array(
'Cars' => array(
'honda' => array(
'Red',
'Blue',
'Yellow',
)
)
)
);
function getTotalDepth($array) {
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
$max = 0;
foreach ($iterator as $element) {
if (!$iterator->callHasChildren()) {
$max = max($max, $iterator->getDepth());
}
}
return $max;
}
echo getTotalDepth($array);
Also very helpful if you want to iterate the complete array:
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $element) {
print_r($element);
echo '<br>';
}

loop through multiple arrays incrementing length of string

I have
$char=array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-");
$doma=array("aero","asia","biz","cat","com","coop","info","int","jobs","mobi","museum","name","net","org","pro","tel","travel","xxx","edu","gov","mil","co.uk","co.nr","co.au","au","ca","co.cc","cc","co","cn","co.jp","de","es","ie","in","it","jp","nl","nz","ru","co.tk","tk","tv","us")
and what I would like to do, is:
from a length of 1 up to a length of 32 arrange the chars into a string, echoing the string, then going back to the beginning again. So eventually my browser would look something like this:
0.aero
1.aero
2.aero
3.aero
....
x.aero
y.aero
z.aero
-.aero
00.aero
01.aero
02.aero
....
za.aero
zb.aero
zc.aero
zd.aero
....
50x90zx908.aero
50x90zx909.aero
50x90zx90a.aero
50x90zx90b.aero
....
50x90zx910.aero
50x90zx911.aero
ect; ect;
How would I create for loops to do this? to include the $doma ones to the end as well each loop?
I know this is huge, but when I've got an idea I gotta try it ;)
If you really want to do this with for loops, then make 33 of them, one for each desired length (1-32) and one for the $doma array.
But I would not do it that way. Instead, observe that the desired combinations of the characters in the $char array actually form a tree. The root node represents the empty string. Each child node of the root represents a 1-character combination ("1", "2", "3", ...). Each child node of those nodes represent a 2-character combination that has the prefix of its parent node (so the children of the "1" node would all start with "1"), and so on. The leaves of the tree would be all 32-character combinations of the characters in $char. If there were only three characters, a, b, and c, it would look something like this:
You can then make a recursive function that implements a depth-first traversal of such a tree, and instead of generating the tree in memory and then printing it, you can just have the function output the contents of each node as it reaches it. Throw in a parameter that allows you to place a suffix after the node contents, and wrap the function in a loop that iterates through all elements in $doma, and you're done.
function f($array, $limit, $suffix, $prefix = "", $counter = 0)
{
if ($counter > 0) {
print "$prefix.$suffix\n";
}
if ($counter < $limit) {
foreach ($array as $element) {
f($array, $limit, $suffix, $prefix . $element, $counter+1);
}
}
}
$char=array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-");
$doma=array("aero","asia","biz","cat","com","coop","info","int","jobs","mobi","museum","name","net","org","pro","tel","travel","xxx","edu","gov","mil","co.uk","co.nr","co.au","au","ca","co.cc","cc","co","cn","co.jp","de","es","ie","in","it","jp","nl","nz","ru","co.tk","tk","tv","us");
foreach ($doma as $d) {
f($char, 32, $d);
}
The order will not be exactly as you specified, but this ordering is logically consistent with the order of elements in the arrays and the depth-first traversal order.
The code basically treats the character combination like a base-35 number. It adds one each loop.
<?php
$char=array("1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-");
$doma=array("aero","asia","biz","cat","com","coop","info","int","jobs","mobi","museum","name","net","org","pro","tel","travel","xxx","edu","gov","mil","co.uk","co.nr","co.au","au","ca","co.cc","cc","co","cn","co.jp","de","es","ie","in","it","jp","nl","nz","ru","co.tk","tk","tv","us");
$combo = array(0,0,0,0,0,0,0,0,0,0); //this stores the ten "digits" of the characters
$pval = 9; //this is the active "place value", the one that you increment
$list = "";
for($i=0;$i<44;$i++) { //loops through doma
for($j=0;$j<2758547353515625;$j++) { //loops through character combos, that long number is the permutations
for($l=0;$l<10;$l++) { //loop displays combo
$list .= $char[$combo[$l]];
}
$list .= "." . $doma[$i] . "<br/>"; //add combo to list
/*This next part check to see if the active digit is 35. It is is, it sets it
equal to zero and looks to the digit on the left. It repeats this until it
no longer finds a 35. This is like going from 09 to 10 in the decimal system. */
if($combo[$pval] == 35) {
while($combo[$pval] == 35) {
$combo[$pval] = 0;
$pval--;
}
}
$combo[$pval]++; //whatever digit it left on gets incremented.
$pval = 9; //reset, go back to first place value
}
for($l=0;$l<10;$l++) {
$combo[$l] = 0; //reset combo for the next top level domain
}
}
echo $list; //print the compiled list.
?>

How to find leaf arrays in nested arrays?

I have a nested array in PHP:
array (
'0' => "+5x",
'1' => array (
'0' => "+",
'1' => "(",
'2' => "+3",
'3' => array (
'0' => "+",
'1' => "(",
'2' => array ( // I want to find this one.
'0' => "+",
'1' => "(",
'2' => "+5",
'3' => "-3",
'4' => ")"
),
'3' => "-3",
'4' => ")"
),
'4' => ")"
)
);
I need to process the innermost arrays, ones that themselves contain no arrays. In the example, it's the one with the comment: "I want to find this one." Is there a function for that?
I have thought about doing (written as an idea, not as correct PHP):
foreach ($array as $id => $value) {
if ($value is array) {
$name = $id;
foreach ($array[$id] as $id_2 => $value_2) {
if ($value_2 is array) {
$name .= "." . $id_2;
foreach ($array[$id][$id_2] as $id_3 => $value_3) {
if ($value_3 is array) {
$name .= "." . $id_3;
foreach ($array[$id][$id_2][$id_3] as $id_4 => $value_4) {
if ($value_4 is array) {
$name .= "." . $id_4;
foreach [and so it goes on];
} else {
$listOfInnerArrays[] = $name;
break;
}
}
} else {
$listOfInnerArrays[] = $name;
break;
}
}
} else {
$listOfInnerArrays[] = $name;
break;
}
}
}
}
So what it does is it makes $name the current key in the array. If the value is an array, it goes into it with foreach and adds "." and the id of the array. So we would in the example array end up with:
array (
'0' => "1.3.2",
)
Then I can process those values to access the inner arrays.
The problem is that the array that I'm trying to find the inner arrays of is dynamic and made of a user input. (It splits an input string where it finds + or -, and puts it in a separate nested array if it contains brackets. So if the user types a lot of brackets, there will be a lot of nested arrays.)
Therefore I need to make this pattern go for 20 times down, and still it will only catch 20 nested arrays no matter what.
Is there a function for that, again? Or is there a way to make it do this without my long code? Maybe make a loop make the necessary number of the foreach pattern and run it through eval()?
Definitions
simple:
Describes expressions without sub-expressions (e.g. "5", "x").
compound:
Describes expressions that have sub-expressions (e.g. "3+x", "1+2").
constness:
Whether an expression has a constant value (e.g. "5", "1+2") or not (e.g. "x", "3+x").
outer node:
In an expression tree, a node reachable by always traversing left or always traversing right. "Outer" is always relative to a given node; a node might be "outer" relative to one node, but "inner" relative to that node's parent.
inner node:
In an expression tree, a node that isn't an outer node.
For an illustration of "inner" and "outer" nodes, consider:
__1__
/ \
2 5
/ \ / \
3 4 6 7
3 and 7 are always outer nodes. 6 is outer relative to 5, but inner relative to 1.
Answer
The difficulty here lies more in the uneven expression format than the nesting. If you use expression trees, the example 5x+3=(x+(3+(5-3))) equation would parse to:
array(
'=' => array(
'+' => array( // 5x + 3
'*' => array(
5, 'x'
),
3
)
'+' => array( // (x+(3+(5-3)))
'x',
'+' => array( // (3+(5-3))
3,
'-' => array(
5, 3
) ) ) ) )
Note that nodes for binary operations are binary, and unary operations would have unary nodes. If the nodes for binary commutative operations could be combined into n-ary nodes, 5x+3=x+3+5-3 could be parsed to:
array(
'=' => array(
'+' => array( // 5x + 3
'*' => array(
5, 'x'
),
3
)
'+' => array( // x+3+5-3
'x',
3,
'-' => array(
5, 3
) ) ) )
Then, you'd write a post-order recursive function that would simplify nodes. "Post-order" means node processing happens after processing its children; there's also pre-order (process a node before its children) and in-order (process some children before a node, and the rest after). What follows is a rough outline. In it, "thing : Type" means "thing" has type "Type", and "&" indicates pass-by-reference.
simplify_expr(expression : Expression&, operation : Token) : Expression {
if (is_array(expression)) {
foreach expression as key => child {
Replace child with simplify_expr(child, key);
key will also need to be replaced if new child is a constant
and old was not.
}
return simplify_node(expression, operation);
} else {
return expression;
}
}
simplify_node(expression : Expression&, operation : Token) : Expression;
In a way, the real challenge is writing simplify_node. It could perform a number of operations on expression nodes:
If an inner grand-child doesn't match the constness of the other child but its sibling does, swap the siblings. In other words, make the odd-man-out an outer node. This step is in preparation for the next.
+ + + +
/ \ / \ / \ / \
\+ 2 ---> + 2 + y ---> + y
/ \ / \ / \ / \
1 x x 1 x 1 1 x
If a node and a child are the same commutative operation, the nodes could be rearranged. For example, there's rotation:
+ +
/ \ / \
\+ c ---> a +
/ \ / \
a b b c
This corresponds to changing "(a+b)+c" to "a+(b+c)". You'll want to rotate when "a" doesn't match the constness of "b" and "c". It allows the next transformation to be applied to the tree. For example, this step would convert "(x+3)+1" to "x+(3+1)", so the next step could then convert it to "x+4".
The overall goal is to make a tree with const children as siblings. If a commutative node has two const descendants, they can be rotated next to each other. If a node has only one const descendent, make it a child so that a node further up in the hierarchy can potentially combine the const node with another of the ancestor's const children (i.e. const nodes float up until they're siblings, at which point they combine like bubbles in soda).
If all children are constant, evaluate the node and replace it with the result.
Handling nodes with more than one compound child and n-ary nodes left as exercises for the reader.
Object-Oriented Alternative
An OO approach (using objects rather than arrays to build expression trees) would have a number of advantages. Operations would be more closely associated with nodes, for one; they'd be a property of a node object, rather than as the node key. It would also be easier to associate ancillary data with expression nodes, which would be useful for optimizations. You probably wouldn't need to get too deep into the OOP paradigm to implement this. The following simple type hierarchy could be made to work:
Expression
/ \
SimpleExpr CompoundExpr
/ \
ConstantExpr VariableExpr
Existing free functions that manipulate trees would become methods. The interfaces could look something like the following pseudocode. In it:
Child < Parent means "Child" is a subclass of "Parent".
Properties (such as isConstant) can be methods or fields; in PHP, you can implement this using overloading.
(...){...} indicate functions, with the parameters between parentheses and the body between brackets (much like function (...){...} in Javascript). This syntax is used for properties that are methods. Plain methods simply use brackets for the method body.
Now for the sample:
Expression {
isConstant:Boolean
simplify():Expression
}
SimpleExpr < Expression {
value:Varies
/* simplify() returns an expression so that an expression of one type can
be replaced with an expression of another type. An alternative is
to use the envelope/letter pattern:
http://users.rcn.com/jcoplien/Patterns/C++Idioms/EuroPLoP98.html#EnvelopeLetter
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Envelope_Letter
*/
simplify():Expression { return this }
}
ConstantExpr < SimpleExpr {
isConstant:Boolean = true
}
VariableExpr < SimpleExpr {
isConstant:Boolean = false
}
CompoundExpr < Expression {
operation:Token
children:Expression[]
commutesWith(op:Expression):Boolean
isCommutative:Boolean
isConstant:Boolean = (){
for each child in this.children:
if not child.isConstant, return false
return true
}
simplify():Expression {
for each child& in this.children {
child = child.simplify()
}
return this.simplify_node()
}
simplify_node(): Expression {
if this.isConstant {
evaluate this, returning new ConstExpr
} else {
if one child is simple {
if this.commutesWith(compound child)
and one grand-child doesn't match the constness of the simple child
and the other grand-child matches the constness of the simple child
{
if (compound child.isCommutative):
make odd-man-out among grand-children the outer child
rotate so that grand-children are both const or not
if grand-children are const:
set compound child to compound child.simplify_node()
}
} else {
...
}
}
return this
}
}
The PHP implementation for SimpleExpr and ConstantExpr, for example, could be:
class SimpleExpr extends Expression {
public $value;
function __construct($value) {
$this->value = $value;
}
function simplify() {
return $this;
}
}
class ConstantExpr extends SimpleExpr {
// Overloading
function __get($name) {
switch ($name) {
case 'isConstant':
return True;
}
}
}
An alternate implementation of ConstantExpr:
function Expression {
protected $_properties = array();
// Overloading
function __get($name) {
if (isset($this->_properties[$name])) {
return $this->_properties[$name];
} else {
// handle undefined property
...
}
}
...
}
class ConstantExpr extends SimpleExpr {
function __construct($value) {
parent::construct($value);
$this->_properties['isConstant'] = True;
}
}
Recursive foreach function, from comments at: http://php.net/manual/en/control-structures.foreach.php
/* Grab any values from a multidimensional array using infinite recursion. --Kris */
function RecurseArray($inarray, $result) {
foreach ($inarray as $inkey => $inval) {
if (is_array($inval)) {
$result = RecurseArray($inval, $result);
} else {
$result[] = $inval;
}
}
return $result;
}
Note that the above implementation produces a flattened array. To preserve nesting:
function RecurseArray($inarray) {
$result = array();
foreach ( $inarray as $inkey => $inval ) {
if ( is_array($inval) ) {
$result[] = RecurseArray($inval);
} else {
// process $inval, store in result array
$result[] = $inval;
}
}
return $result;
}
To modify an array in-place:
function RecurseArray(&$inarray) {
foreach ( $inarray as $inkey => &$inval ) {
if ( is_array($inval) ) {
RecurseArray($inval);
} else {
// process $inval
...
}
}
}
RecursiveIteratorIterator knows the current depth of any children. As you're interested only in children that have children, filter those with no children out and look for max-depth.
Then filter again based by depth for max-depth:
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST);
$cf = new ChildrenFilter($ritit);
$maxdepth = NULL;
foreach($cf as $v)
{
$maxdepth = max($maxdepth, $cf->getDepth());
}
if (NULL === $maxdepth)
{
throw new Exception('No children found.');
}
$df = new DepthFilter($cf, $maxdepth);
foreach($df as $v)
{
echo "Array with highest depth:\n", var_dump($v), "\n";
}
Demo / Source
Please, try the following code and let me know the results.
You just need to pass your array to the find_deepest function.
function find_deepest( $array )
{
$index = ''; // this variable stores the current position (1.2, 1.3.2, etc.)
$include = true; // this variable indicates if the current position should be added in the result or not
$result = array(); // this is the result of the function, containing the deepest indexes
$array_stack = array(); // this is a STACK (or LIFO) to temporarily store the sub-arrays - see http://en.wikipedia.org/wiki/LIFO_%28computing%29
reset( $array ); // here we make the array internal POINTER move to the first position
// each loop interaction moves the $array internal pointer one step forward - see http://php.net/each
// if $current value is null, we reached the end of $array; in this case, we will also continue the loop, if the stack contains more than one array
while ( ( $current = each( $array ) ) || ( count( $array_stack ) > 1 ) )
{
// we are looping $array elements... if we find an array (a sub-array), then we will "enter it...
if ( is_array( $current['value'] ) )
{
// update the index string
$index .= ( empty ( $index ) ? '' : '.' ) . $current['key'];
// we are entering a sub-array; by default, we will include it
$include = true;
// we will store our current $array in the stack, so we can move BACK to it later
array_push( $array_stack, $array );
// ATTENTION! Here we CHANGE the $array we are looping; here we "enter" the sub-array!
// with the command below, we start to LOOP the sub-array (whichever level it is)
$array = $current['value'];
}
// this condition means we reached the END of a sub-array (because in this case "each()" function has returned NULL)
// we will "move out" of it; we will return to the previous level
elseif ( empty( $current ) )
{
// if we reached this point and $include is still true, it means that the current array has NO sub-arrays inside it (otherwise, $include would be false, due to the following lines)
if ( $include )
$result[] = $index;
// ATTENTION! With the command below, we RESTORE $array to its precedent level... we entered a sub-array before, now we are goin OUT the sub-array and returning to the previous level, where the interrupted loop will continue
$array = array_pop( $array_stack );
// doing the same thing with the $index string (returning one level UP)
$index = substr( $index, 0, strrpos( $index, '.' ) );
// if we are RETURNING one level up, so we do NOT want the precedent array to be included in the results... do we?
$include = false;
}
// try removing the comment from the following two lines! you will see the array contents, because we always enter this "else" if we are not entering a sub-array or moving out of it
// else
// echo $index . ' => ' . $current['value'] . '<br>';
}
return $result;
}
$result = find_deepest( $my_array );
print_r( $result );
The most important parts of the code are:
the each command inside the while loop
the array_push function call, where we store the current array in the "array stack" in order to return back to it later
the array_pop function call, where we return one level back by restoring the current array from the "array stack"

Regular Expression to match unlimited number of options

I want to be able to parse file paths like this one:
/var/www/index.(htm|html|php|shtml)
into an ordered array:
array("htm", "html", "php", "shtml")
and then produce a list of alternatives:
/var/www/index.htm
/var/www/index.html
/var/www/index.php
/var/www/index.shtml
Right now, I have a preg_match statement that can split two alternatives:
preg_match_all ("/\(([^)]*)\|([^)]*)\)/", $path_resource, $matches);
Could somebody give me a pointer how to extend this to accept an unlimited number of alternatives (at least two)? Just regarding the regular expression, the rest I can deal with.
The rule is:
The list needs to start with a ( and close with a )
There must be one | in the list (i.e. at least two alternatives)
Any other occurrence(s) of ( or ) are to remain untouched.
Update: I need to be able to also deal with multiple bracket pairs such as:
/var/(www|www2)/index.(htm|html|php|shtml)
sorry I didn't say that straight away.
Update 2: If you're looking to do what I'm trying to do in the filesystem, then note that glob() already brings this functionality out of the box. There is no need to implement a custom solutiom. See #Gordon's answer below for details.
I think you're looking for:
/(([^|]+)(|([^|]+))+)/
Basically, put the splitter '|' into a repeating pattern.
Also, your words should be made up 'not pipes' instead of 'not parens', per your third requirement.
Also, prefer + to * for this problem. + means 'at least one'. * means 'zero or more'.
Not exactly what you are asking, but what's wrong with just taking what you have to get the list (ignoring the |s), putting it into a variable and then explodeing on the |s? That would give you an array of however many items there were (including 1 if there wasn't a | present).
Non-regex solution :)
<?php
$test = '/var/www/index.(htm|html|php|shtml)';
/**
*
* #param string $str "/var/www/index.(htm|html|php|shtml)"
* #return array "/var/www/index.htm", "/var/www/index.php", etc
*/
function expand_bracket_pair($str)
{
// Only get the very last "(" and ignore all others.
$bracketStartPos = strrpos($str, '(');
$bracketEndPos = strrpos($str, ')');
// Split on ",".
$exts = substr($str, $bracketStartPos, $bracketEndPos - $bracketStartPos);
$exts = trim($exts, '()|');
$exts = explode('|', $exts);
// List all possible file names.
$names = array();
$prefix = substr($str, 0, $bracketStartPos);
$affix = substr($str, $bracketEndPos + 1);
foreach ($exts as $ext)
{
$names[] = "{$prefix}{$ext}{$affix}";
}
return $names;
}
function expand_filenames($input)
{
$nbBrackets = substr_count($input, '(');
// Start with the last pair.
$sets = expand_bracket_pair($input);
// Now work backwards and recurse for each generated filename set.
for ($i = 0; $i < $nbBrackets; $i++)
{
foreach ($sets as $k => $set)
{
$sets = array_merge(
$sets,
expand_bracket_pair($set)
);
}
}
// Clean up.
foreach ($sets as $k => $set)
{
if (false !== strpos($set, '('))
{
unset($sets[$k]);
}
}
$sets = array_unique($sets);
sort($sets);
return $sets;
}
var_dump(expand_filenames('/(a|b)/var/(www|www2)/index.(htm|html|php|shtml)'));
Maybe I'm still not getting the question, but my assumption is you are running through the filesystem until you hit one of the files, in which case you could do
$files = glob("$path/index.{htm,html,php,shtml}", GLOB_BRACE);
The resulting array will contain any file matching your extensions in $path or none. If you need to include files by a specific extension order, you can foreach over the array with an ordered list of extensions, e.g.
foreach(array('htm','html','php','shtml') as $ext) {
foreach($files as $file) {
if(pathinfo($file, PATHINFO_EXTENSION) === $ext) {
// do something
}
}
}
Edit: and yes, you can have multiple curly braces in glob.
The answer is given, but it's a funny puzzle and i just couldn't resist
function expand_filenames2($str) {
$r = array($str);
$n = 0;
while(preg_match('~(.*?) \( ( \w+ \| [\w|]+ ) \) (.*) ~x', $r[$n++], $m)) {
foreach(explode('|', $m[2]) as $e)
$r[] = $m[1] . $e . $m[3];
}
return array_slice($r, $n - 1);
}
print_r(expand_filenames2('/(a|b)/var/(ignore)/(www|www2)/index.(htm|html|php|shtml)!'));
maybe this explains a bit why we like regexps that much ;)

Categories