PHP - create dynamic multidimensional file tree array - php

I want to create a file tree, and for this purpose I need to convert an array of files and directories to a multidimensional file tree array. For example:
array
(
'file.txt',
'dir1/',
'dir1/dir2/',
'dir1/dir2/dir3/',
'dir1/file.txt',
)
to
array
(
'file.txt',
'dir1' =>
array
(
'dir2' =>
array
(
'dir3' =>
array(),
),
'file.txt',
)
)
I've tried several functions to accomplish this, but non of them worked. The problem I've encountered for example that there is no easy way to convert an array ('test','test','test'),'test' to $array['test']['test']['test'] = 'test'.

Here's a shorter recursive one:
function dir_tree($dir) {
$files = array_map('basename', glob("$dir/*"));
foreach($files as $file) {
if(is_dir("$dir/$file")) {
$return[$file] = dir_tree("$dir/$file");
} else {
$return[] = $file;
}
}
return $return;
}

Take a look to my post here.
The answer is: strtok will save you.
<?php
$input = [
'/RootFolder/Folder1/File1.doc',
'/RootFolder/Folder1/SubFolder1/File1.txt',
'/RootFolder/Folder1/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc',
];
function parseInput($input) {
$result = array();
foreach ($input AS $path) {
$prev = &$result;
$s = strtok($path, '/');
while (($next = strtok('/')) !== false) {
if (!isset($prev[$s])) {
$prev[$s] = array();
}
$prev = &$prev[$s];
$s = $next;
}
$prev[] = $s;
unset($prev);
}
return $result;
}
var_dump(parseInput($input));
Output :
array(1) {
["RootFolder"]=>
array(2) {
["Folder1"]=>
array(2) {
[0]=>
string(9) "File1.doc"
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File1.txt"
[1]=>
string(9) "File2.txt"
}
}
["Folder2"]=>
array(1) {
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File2.txt"
["SubSubFolder1"]=>
array(1) {
[0]=>
string(9) "File4.doc"
}
}
}
}
}

I have PHP snippet for that:
<?php
function wps_glob($dir) {
foreach (glob($dir . '/*') as $f) {
if(is_dir($f)) {
$r[] = array(basename($f) => wps_glob($f));
}
else {
$r[] = basename($f);
}
}
return $r;
}
function wps_files($path) {
$wpsdir = Array(
'root' => $path,
'struktur' => wps_glob($path)
);
return $wpsdir;
}
?>
example usage here

Related

how to add child array with dynamic key in loop PHP

i have string like this
$string = 'root.1.child1.2.nextnode.3.anothernode.4.var';
exploded by "." and created array like this
$arr = array('root','1','child1','2','nextnode','3','anothernode','3','var');
how i can convert this array to something like this ?
it should be dynamically convert because in some cases nodes in string are in a number different with the sample .
["root"]=>
array(1) {
[1]=>
array(1) {
["child1"]=>
array(1) {
[2]=>
array(1) {
["nextnode"]=>
array(1) {
[3]=>
array(1) {
["anothernode"]=>
array(1) {
[3]=>
array(1) {
[var]=>
NULL
}
}
}
}
}
}
}
}
An example using recursive function.
$array = ['root', '1', 'child1', '2', 'nextnode', '3', 'anothernode', '3', 'var'];
function getNestedArray(array $arr, int $idx = 0) {
if ($idx + 1 <= count($arr)) {
return [$arr[$idx] => getNestedArray($arr, $idx + 1)];
}
return null;
}
$output = getNestedArray($array);
var_dump($output);
This can be quit easily achieved by referencing the output and looping over the exploded array:
$output = [];
$reference = &$output;
foreach ($arr as $el) {
if (is_numeric($el)) {
$el = (int)$el;
}
$reference = [];
$reference[$el] = null;
$reference = &$reference[$el];
}
This also checks whether the element is a number and casts it to an integer if it is. The $output variable will contain the final array.
You can use recursive function
to do though
$flatArray = array('root','1','child1','2','nextnode','3','anothernode','3','var'); // your array
function createNestedArray($flatArray)
{
if( sizeof($flatArray) == 1 ) {
return [ $flatArray[0] => null ]; // for the case that paramter has one member we need to return [ somename => null ]
}
$nestedArray[ $flatArray[0] ] = createNestedArray(array_slice($flatArray, 1)); // otherwise we need to call createNestedArray with rest of array
return $nestedArray;
}
$nestedArray = createNestedArray($flatArray); // the result

PHP arrray and string

I have problems with arrays. When I try to get the first array [0] it does not give me anything.
This is output
array(4) { [0]=> string(0) "" [333]=> string(123) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/f/de/d6/fded6f1587f863a9e8fc1c2173143a8782fa655e/700Wx700H-105395-0416.jpg" [334]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/e/b9/54/eb954216442547d2ed2c71adbcf73d4f2b3ef903/700Wx700H-105395-a-0416.jpg" [335]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/7/16/95/71695917dd17d29648c8f4907000e3c6cab64581/700Wx700H-105395-b-0416.jpg" }
and this is code
private function getImages($dom) {
$images = [];
foreach ($dom->getElementsByTagName('ul') as $ul) {
if ($ul->getAttribute('class') == 'image-thumbnails') {
foreach ($dom->getElementsByTagName('li') as $li) {
$images[] = $li->getAttribute('data-zoom-url');
}
}
}
$images = array_unique($images);
return $images;
}
If you want to exclude empty values, check if the attribute is empty before adding it to the array:
if(!empty($li->getAttribute('data-zoom-url'))) {
$images[] = $li->getAttribute('data-zoom-url');
}

Delete some data from Array in php

I want to delete some data from an array in PHP. Here is the array:
array(4) {
[0]=> array(1) { ["image"]=> string(20) "w85YrKChBGTZ9fQS.jpg" }
[1]=> array(1) { ["image"]=> string(20) "3buahEs6rRWFdYez.jpg" }
[2]=> array(1) { ["image"]=> string(20) "gYPtDrx3sFzkVENB.jpg" }
[3]=> array(1) { ["image"]=> string(20) "JE3rodDvs6521cFm.jpg" }
}
Here is my method and where I am deleting:
public function deleteImage(){
foreach (getCarImages() as $array){
//var_dump($array).'<br>';
$index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
if($index !== FALSE){
var_dump($index).'<br>';
unset($array[$index]);
}else{
echo '<br>else here';
}
}
}
And here is the result of deleteImage()
string(5) "image"
else
here
else
here
else
here
I am confused. How can I delete a nested array from the main array.
If you need to delete a whole subarray from array, then use array_flter function:
public function deleteImage(){
return array_filter(getCarImages(), function ($v) {
return $v['image'] != 'w85YrKChBGTZ9fQS.jpg';
});
}
Update: Anonymous function doesn't know about $imageName variable. You have to use it:
public function deleteImage($imageName = null)
{
$myarray = array_filter(
getCarImages(),
function ($v) use ($imageName) { return $v['image'] != $imageName; }
);
}
You can trans the images as a reference to the function.
public function deleteImage(&$images){
foreach ($images as $k => $array){
//var_dump($array).'<br>';
$index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
if($index !== FALSE){
var_dump($index).'<br>';
unset($images[$k]);
}else{
echo '<br>else here';
}
}
}

PHP Str_replace is not working in foreach loop

Here is my code.
I am trying to get inspect link for steam item. I have tried to use preg_replace but no luck either.
$API_link = sprintf("http://steamcommunity.com/id/*steamid*/inventory/json/730/2?trading=1");
$json = file_get_contents($API_link);
$json_output = json_decode($json);
$result = $json_output;
$link = array();
$id = array();
foreach($result->rgDescriptions AS $item){
$empty = array();
$newstring = $item->actions[0]->link;
if($newstring == NULL){
continue;
} else {
$empty['link'] = $newstring;
array_push($link, $empty);
}
}
foreach($result->rgInventory AS $inventory){
$empty = array();
if($inventory->instanceid == 0){
continue;
} else {
$empty['id'] = $inventory->id;
array_push($id, $empty);
}
}
$array = array_merge($id, $link);
foreach($array AS $final){
$assetid = "%assetid%";
echo str_replace($assetid, $final['id'], $final['link']);
}
}
But its not working. Please see if you can help.
As I can see you have array of arrays:
// bracket squares equivalent of array() keyword PHP >=v5.4
// here is
// $link = array(['link'=>'url'],['link'=>'url'])
// $id = array(['id'=>'id'],['id'=>'id'])
// result will be:
// array(['link']=>'url'],['link'=>'url'],['id'=>'id'],['id'=>'id'])
$array = array_merge($id, $link);
foreach($array AS $final){
// here is the first $final
// array('link'=>'url')
$assetid = "%assetid%";
// but here is we try to get
// 'id' and 'link'
echo str_replace($assetid, $final['id'], $final['link']);
}
I think it's some kind of mistake.
Ok, some test script:
<?php
$a = array( array('link'=>'hello1'), array('link'=>'hello2'));
$b = array( array('id'=>'id0'), array('id'=>'id1'));
$c = array_merge($a, $b);
var_dump($c);
result:
array(4) {
[0] =>
array(1) {
'link' =>
string(6) "hello1"
}
[1] =>
array(1) {
'link' =>
string(6) "hello2"
}
[2] =>
array(1) {
'id' =>
string(3) "id0"
}
[3] =>
array(1) {
'id' =>
string(3) "id1"
}
}
array_merge doesn't mix your associative arrays between them nether all nor particular item (I hope I explain it correct)
of course
foreach ($c as $item) {
var_dump($item);
}
will enumerate all the items one by one
array(1) {
'link' =>
string(6) "hello1"
}
array(1) {
'link' =>
string(6) "hello2"
}
array(1) {
'id' =>
string(3) "id0"
}
array(1) {
'id' =>
string(3) "id1"
}
and there is no array that has both of them (link and id) in the item
This script can't associate link and id properly, cause some of links can be skipped by continue, some of id also can be skipped. And it will be just a random list of available information. You can stuck in the next situation:
- $links has first 10 links
- $id has 3,4,5,7,9,11
It's just a list. Even if you have only this pure info (no other details), you can't properly associate it between of them by using shown source.
Here is minimum 1 simple solutions:
don't skip, don't merge, just add an empty array, and your final loop will be like this:
$assetid = "%assetid%";
for ($link as $key=>$final) {
if (count($final) && count($id[$key])) {
echo str_replace($assetid, $id[$key]['id'], $final['link']);
} else {
// some of needed arguments absent
}
}
Description not enough. Maybe try dump some variables?
foreach($array AS $final){
$assetid = "%assetid%";
//Check what is in $final
var_dump($final);
echo str_replace($assetid, $final['id'], $final['link']);
}

php multidimensional array to single dimensional array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 months ago.
I have an array
array(5) {
[0]=>
array(1) {
["id"]=>
string(1) "5"
}
[1]=>
array(1) {
["id"]=>
string(1) "6"
}
[2]=>
array(1) {
["id"]=>
string(1) "7"
}
[3]=>
array(1) {
["id"]=>
string(1) "8"
}
[4]=>
array(1) {
["id"]=>
string(1) "9"
}
}
I wan to make my array like:
$registrationIDs = array( "5","6","7","8","9");
I am trying this code but not working
$results = array();
foreach($result as $inner) {
$results[key($inner)] = current($inner);
}
How do I effeciently transform arrays like this
Try with array_map.
$results = array_map (function ($e) { return $e['id']; }, $inner);
http://php.net/manual/en/function.array-map.php
By the way, if you still want to do it your way, try this form of foreach :
$results = array ();
foreach ($inner as $key => $value)
$results[$key] = $value['id'];
$array = [['id'=>1],['id'=>2],['id'=>3],['id'=>4],['id'=>5],];
$result = call_user_func_array('array_merge_recursive', $array);
var_dump($result['id']);
//array(5) {
// [0] =>
// int(1)
// [1] =>
// int(2)
// [2] =>
// int(3)
// [3] =>
// int(4)
// [4] =>
// int(5)
//}
Ok, I saw a lot of answers, so I wondered what to better answer was.
<?php
$data = array ();
for ($i = 0; $i < 1000000; $i++)
$data[$i] = array ('id' => rand ());
$time0 = microtime (true);
// Niols (1)
$results = array_map (function ($e) { return $e['id']; }, $data);
$time1 = microtime (true);
// Niols (2)
$results = array ();
foreach ($data as $key => $value)
$results[$key] = $value['id'];
$time2 = microtime (true);
// User (1)
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$results = iterator_to_array($it, false);
$time3 = microtime (true);
// User (2)
$results = array();
foreach ($data as $datum)
$results = array_merge($results, $datum);
$time4 = microtime (true);
// sectus
$results = call_user_func_array('array_merge_recursive', $data);
$time5 = microtime (true);
// Pankaj katiyar and Ghost
$results = array_column($data, 'id');
$time6 = microtime (true);
var_dump ($time1-$time0);
var_dump ($time2-$time1);
var_dump ($time3-$time2);
var_dump ($time4-$time3);
var_dump ($time5-$time4);
var_dump ($time6-$time5);
On my computer, this outputs :
float(0.62708687782288)
float(0.35285401344299)
float(1.5429890155792)
float(0.7408618927002)
float(0.70525908470154)
float(0.15015292167664)
Conclusion :
array_column is ultra-efficient (but PHP 5.5+). Writing a simple foreach seems quite efficient too.
You can try with below code.
I think this is working fine.
Process 1:-
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$l = iterator_to_array($it, false);
var_dump($l); // one Dimensional
Process 2:-
Try with:
$input = array(/* your array*/);
$output = array();
foreach ( $input as $data ) {
$output = array_merge($output, $data);
}
Try this:
$array = array(/*your array*/);
$results = array();
foreach ($array as $value)
{
foreach($value as $innerValue)
{
$results[] = $innervalue;
}
}

Categories