logo
down
shadow

In PHP... best way to turn string representation of a folder structure into nested array


In PHP... best way to turn string representation of a folder structure into nested array

Content Index :

In PHP... best way to turn string representation of a folder structure into nested array
Tag : php , By : smbrant
Date : January 10 2021, 01:49 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Ruby: Parsing a string representation of nested arrays into an Array?


Tag : ruby , By : LucaN
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Let's say I had the string , That particular example is being parsed correctly using JSON:
s = "[1,2,[3,4,[5,6]],7]"
#=> "[1,2,[3,4,[5,6]],7]"
require 'json'
#=> true
JSON.parse s
#=> [1, 2, [3, 4, [5, 6]], 7]
def my_scan s
  res = []
  s.scan(/((\d+)|(\[(.+)\]))/) do |match|
    if match[1]
      res << match[1].to_i
    elsif match[3]
      res << my_scan(match[3])
    end
  end
  res
end

s = "[1,2,[3,4,[5,6]],7]"
p my_scan(s).first #=> [1, 2, [3, 4, [5, 6]], 7]

Convert string representation of nested array to Array


Tag : ruby-on-rails , By : evegter
Date : March 29 2020, 07:55 AM
seems to work fine I have a string representation of array: , You can use YAML.load:
require 'yaml'    
YAML.load(val1.delete ':').map{|x| x.map(&:to_sym)}
# => [[:one, :two], [:four, :one]]
eval(val1).map{|x| x.map(&method(:eval))}
# => [[:one, :two], [:four, :one]]

How can I create a nested object representation of a folder structure


Tag : arrays , By : Mark W
Date : March 29 2020, 07:55 AM
it should still fix some issue So I need to get a flat array and a nested object that represents a folder structure. It does however need to filter out certain folder that do not have certain files (FILE.txt) inside of them and ignore files all together. , Here's my take on the code:
const flat = [
  "folder0",
  "folder1",
  "folder1/subfolder1",
  "folder1/subfolder2",
  "folder1/subfolder3",
  "folder1/subfolder3/subsubfolder1",
  "folder1/subfolder3/subsubfolder2"
];
const nested = {};
const add = (source, target) => {
  const elements = source.split("/");
  const element = elements.shift();
  target[element] = target[element] || element;
  if (elements.length) {
    target[element] = typeof target[element] === "object" ? target[element] : {};
    add(elements.join("/"), target[element]);
  }
};

flat.forEach(item => add(item, nested));

console.log(nested);

Convert multidimensional array of folder paths to a nested folder structure array


Tag : javascript , By : Lord Zantor
Date : March 29 2020, 07:55 AM
I wish this helpful for you I managed to achieve my goal. I did it with the below code, which is the complete code. I even managed to skip the first array form and generate the second form instantly (see my question for the arrays I mean). My solution:
window.onload = function() {
    var data = [], dataLength, datanest, datanestLength;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var doc = this.responseXML,
                tr = doc.getElementsByTagName('tr'), trLength = tr.length;

            var filedir, level, levelLength;
            for (var i = 1; i < trLength; i++) {
                filedir = tr[i].getElementsByTagName('td')[7].innerHTML;
                // filedir is formed like "foldername\foldername\filename.ext" etc.
                level = filedir.split('\\');
                levelLength = level.length;
                for (var j = 0; j < levelLength; j++) {

                    if (j == 0 && j < levelLength - 1) {
                        dataLength = data.length;
                        if (dataLength == 0 ||
                            data[dataLength - 1].type == 'file' ||
                            data[dataLength - 1].Name !== level[j]) {
                            data.push({
                                type: 'folder',
                                Name: level[j],
                                content: []
                            });
                        }
                        datanest = data[data.length - 1].content;

                    } else if (j < levelLength - 1) {
                        datanestLength = datanest.length;
                        if (datanestLength == 0 ||
                            datanest[datanestLength - 1].type == 'file' ||
                            datanest[datanestLength - 1].Name !== level[j]) {
                            datanest.push({
                                type: 'folder',
                                Name: level[j],
                                content: []
                            });
                        }
                        datanest = datanest[datanest.length - 1].content;

                    } else {
                        if (j == 0) { datanest == data; }
                        datanest.push({
                            type: 'file',
                            Track: tr[i].getElementsByTagName('td')[3].innerHTML,
                            Title: tr[i].getElementsByTagName('td')[0].innerHTML,
                            Artist: tr[i].getElementsByTagName('td')[1].innerHTML,
                            Time: tr[i].getElementsByTagName('td')[2].innerHTML,
                            Release: tr[i].getElementsByTagName('td')[4].innerHTML,
                            'Release Date': tr[i].getElementsByTagName('td')[8].innerHTML,
                            Label: tr[i].getElementsByTagName('td')[5].innerHTML,
                            Genre: tr[i].getElementsByTagName('td')[6].innerHTML,
                            File: level[j]
                        });
                    }
                }
            }
            console.log(data);//SUCCESS
        }
    };
    xhttp.open('GET', 'backup.xml', true);
    xhttp.send();
};

How to turn a dict with absolute file paths into a folder-structure-like nested Dict?


Tag : python , By : uxn
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I have a dict like: , You can use itertools.groupby with recursion:
from itertools import groupby as gb
def group(d):
  new_d = [(a, list(b)) for a, b in gb(sorted(d, key=lambda x:x[0][0]), key=lambda x:x[0][0])]
  return {a:b[-1][-1] if not b[0][0][1:] else group([(c, k) for [_, *c], k in b]) for a, b in new_d}

source_dict = {"/a": {"foo": "bar", "randomstuff": 3}, "/b/a": {"some":"thing", "else":{"bx": 1}}, "/b/g/h/g": {"any": "value"}}
r = {'/':group([(list(filter(None, a.split('/'))), b) for a, b in source_dict.items()])}
{'/': {'a': {'foo': 'bar', 'randomstuff': 3}, 'b': {'a': {'some': 'thing', 'else': {'bx': 1}}, 'g': {'h': {'g': {'any': 'value'}}}}}}
Related Posts Related QUESTIONS :
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • Creating a new data entry into a database with eloquent and trying to access the variable in the url
  • How to test authentication using Laravel Dusk?
  • PHP parse_str not getting all $_GET variables
  • Variable issues in php class
  • Get orders between dates in Codeigniter
  • Eloquent Special Chars Issue
  • Keeping leading zeros column Mysql
  • Current level navigation in Wordpress
  • Add a custom text to WooCommerce cart items if the product has a specific shipping class
  • Error connecting to CommissionJunction Token : [60] SSL certificate problem: unable to get local issuer certificate
  • How do I add a new key value pair to an object in PHP?
  • Http post request to php with dart
  • How to add a route in with blade into parameters of a component
  • How can i get the source of a 777 - CHMOD php file?
  • Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon"
  • How can I hide a $_GET variable to be more secured in PHP?
  • Login to Gmail Inbox using Curl?
  • Upload Excel or CSV file to MySQL with PHP
  • Outlook Marking Email as Junk Email
  • Upload an image using class.upload.php via AJAX, display image in form using jQuery
  • mysql_connect() causes page to not display (WAMP)
  • How to limit a users uploaded image size using PHP
  • What's the difference whether or not to run PHP in safe mode?
  • Logging in to a website cURL
  • Using php to create a password system with chinese characters
  • PHP is not called properly in IE using set interval function in Javascript
  • How to read pdf, ppt, xl, doc files content into a string in php/python
  • php script for currency conversion
  • PayPal for Indian Rupees (INR) any solution
  • PHP Deployment to Live Server
  • Ideal Multi-Developer Lamp Stack?
  • How can I save an image from a file input field using PHP & MySQL?
  • Warning: array_multisort() [function.array-multisort]: Argument #1 is expected to be an array or a sort flag in
  • Connecting to external MySQL DB from a web server not running MySQL
  • Is it possible to add custom fields to a Drupal taxonomy term?
  • PHP 6.0 - Roadmap?
  • jQuery wait for ajax call to be over before continuing
  • checkUnique function?
  • How to define an n-m relation in doctrine?
  • Sort the unsorted text file and rewrite to same text file in sorted order
  • Version control a content management system?
  • How can i run Single PHP File using apache-tomcat-6.0.18?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com