Walk array recursively and print the path of the walk
You could employ a RecursiveIteratorIterator
(docs) to take the hard work out of recursing through the arrays.
function listArrayRecursive($someArray) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
$indent = str_repeat(' ', 10 * $iterator->getDepth());
// Not at end: show key only
if ($iterator->hasChildren()) {
echo "$indent$k :<br>";
// At end: show key, value and path
} else {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode(',', $p);
echo "$indent$k : $v : path -> $path<br>";
}
}
}
get parent array name after array_walk_recursive function
You will have to ditch array_walk_recursive
and roll your own recursive walk. This will allow you to maintain or pass custom state information whenever you recurse.
For example:
function my_walk_recursive(array $array, $path = null) {
foreach ($array as $k => $v) {
if (!is_array($v)) {
// leaf node (file) -- print link
$fullpath = $path.$v;
// now do whatever you want with $fullpath, e.g.:
echo "Link to $fullpath\n";
}
else {
// directory node -- recurse
my_walk_recursive($v, $path.'/'.$k);
}
}
}
How to recursively walk through a directory and print all files in C?
Here is a recursive code that does that:
void sprint(char *filename, char * dirToOpen, int level = 0)
{
DIR *dir;
struct dirent *entry;
struct stat s;
if (!(dir = opendir(dirToOpen)))
return;
if (!(entry = readdir(dir)))
return;
do
{
if(lstat(dirToOpen, &s) == 0 && S_ISDIR(s.st_mode)) /*if it's a directory*/
{
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", dirToOpen, entry->d_name); /*makes pathname*/
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) /*if the directory isn't . or ..*/
continue;
printf("%*s[%s]\n", level * 2, "", entry->d_name);
sprint(filename ,path, level + 1);
}
else
{
if(strcmp(entry->d_name, filename) == 0 || strcmp(filename, ".") == 0) /*if entry name corresponds to filename, print it*/
printf("%*s- %s\n", 2, "", entry->d_name);
}
} while (entry = readdir(dir)); /*while there are more entries to read*/
closedir(dir);
}
Call it with sprint(".", ".");
to recursively walk through a directory and print out all of the files.
Inspired from this answer.
Java- Recursively Get the path of directorys with files on it
See if the following will work for you:
public static void main(String[] args) {
List<Path> listOfDirectoryPaths = new ArrayList<>();
try (Stream<Path> walk = Files.walk(Paths.get("."))) {
walk.forEach(path -> {
if(path.toFile().isFile() && path.toFile().getName().contains(".java")) {
listOfDirectoryPaths.add(path.getParent());
}
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(listOfDirectoryPaths.stream().distinct().collect(Collectors.toList()));
}
}
This will traverse the current directory (.) of where you run it from.
It will look for files that contain ".java"
It will store the Path of the Dir.
Finally, it will return only the distinct paths, so you dont get duplicates.
Try it, and modify it as you see fit.
Scala; recursively walk all directories in parent Hadoop directory
You defined a recursive function that generates an array (for loop) of either:
- the output of the function if the item is a directory, which is an array of objects.
- a
Path
if it is a simple file.
This explains the fact that you obtain nested arrays (array of arrays).
You can use flatMap
to avoid that issue. It transforms (or "flattens") a list of list of objects to a list of objects. Also, to obtain the type you expect, you need to have matching types between your stopping condition and your recursion (Array
of Path
). So you need to wrap hdfsPath
inside an array.
Here is how to quickly fix your problem based on what I just wrote:
def recursiveWalk(hdfsPath: Path): Array[Path] = {
val fs: FileSystem = hdfsPath.getFileSystem(spark.sessionState.newHadoopConf())
val fileIterable = fs.listStatus(hdfsPath)
val res = fileIterable.flatMap(f => {
if (f.isDirectory) {
recursiveWalk(f.getPath).distinct
}
else {
Array(hdfsPath)
}
})
res.distinct
}
The code above fixes the problem but to avoid having to use distinct, you can put the condition on the input file instead of its subfolders like below. You can also define the file system once and for all outside of the function.
val conf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem(conf)
def recursiveWalk(path : Path): Array[Path] = {
if(hdfs.isDirectory(path))
hdfs.listStatus(path).map(_.getPath).flatMap(rec _) :+ path
else Array()
}
Recursive array walk to fetch multi-level array key
You can't with array_walk_recursive
. You will need to use plain array_walk
and provide the recursion yourself:
function test_alter(&$item1, $key, $prefix) {
print $key;
print "<br />";
if(is_array($item1)) {
array_walk($item1, 'test_alter', $prefix);
}
else {
$item1 = "$key $prefix: $item1";
}
}
PHP - Creating path list from array
I hope I understand what you want to achieve. In that case, this could be a solution
<?php
$ids = [
354 => [
368 => [
375,
376
]
],
356,
366
];
$names = [
354 => "Photos",
368 => "Cities",
375 => "England",
376 => "Scotland",
356 => "Files",
366 => "Misc"
];
print_r(build_list($ids));
function build_list($ids, $path = ""){
global $names;
$list = [];
foreach($ids as $key => $value){
if(is_array($value)){
//$list[$key] = $path . $names[$key]; // uncomment if you need output (2)
$list = array_replace_recursive($list, build_list($value, ($path . $names[$key] . "/")))
}else{
$list[$value] = $path . $names[$value];
}
}
return $list;
}
?>
Output (1)
Array
(
[375] => Photos/Cities/England
[376] => Photos/Cities/Scotland
[356] => Files
[366] => Misc
)
Output (2)
Array
(
[354] => Photos
[368] => Photos/Cities
[375] => Photos/Cities/England
[376] => Photos/Cities/Scotland
[356] => Files
[366] => Misc
)
PHP - Array - Recursively print each full branch (up to leaf/leaves) of the nested array (Tree) as an Xpath
First you have to identify that item of body
that contains value == 'sort'
then apply the existing code (extract it in a function first):
$search = 'sort';
// Identify the items having 'value' associated with $search
$allItems = array_filter(
$array['body'],
function (array $item) use ($search) {
// $item contains many tokens, keep $item if the first token has value == 'sort'
// just to be sure you can also check here if $item[0]['token'] is 320 or the value of 'token_org_name'
return $item[0]['value'] == $search;
}
);
// Pass all the found items to the function that produces the path
foreach ($allItems as $item) {
echo(getPath($item)."\n");
}
function getPath(array $array) {
// Collect the values here.
// Start with an empty string to force a leading '/' in the output
$path = array('');
// Walk the array, put the desired values in $path
array_walk_recursive(
$array,
function($value, $key) use (&$path) {
if ($key == 'value' ) {
$path[] = $value;
}
}
);
// Join the collected values and return the result
return implode('/', $path);
}
How to loop through and clean a recursive array (PHP)
you can use array_walk_recursive
like that :
<?php
$arr = array(...);
function clean_all($item,$key)
{
$item = strip_tags($item);
}
array_walk_recursive($arr , 'clean_all');
?>
OR :
this is a recursive function , i think it solves your problem :
<?php
function clean_all($arr)
{
foreach($arr as $key=>$value)
{
if(is_array($value)) $arr[$key] = clean_all($value);
else $arr[$key] = strip_tags($value);
}
return $arr;
}
?>
Related Topics
SQL & PHP - Which Is Faster MySQL_Num_Rows() or 'Select Count()'
Laravel Cannot Delete or Update a Parent Row: a Foreign Key Constraint Fails
Detect In-App Browser (Webview) with PHP/Javascript
How to Set a Maximum Size Limit to PHP Curl Downloads
Fatal Error: Call to a Member Function Query() on Null
Parsing JavaScript (Not JSON) in PHP
Where Do I Put a Database Query in MVC
Finding Free Blocks of Time in MySQL and PHP
JSON Parse Error with Double Quotes
PHP Type-Hinting to Primitive Values
PHP Get All Arguments as Array
Mysql/SQL Retrieve First 40 Characters of a Text Field
How to Use PHP in a JavaScript Function