generating array of parents paths of a URL - php

so if I have a string like this, e.g. "/path1/folder/fun/yay/"
How can I run that through a function to return an array of all the parent paths, looking like this:
array (
'/',
'/path1/',
'/path1/folder/',
'/path1/folder/fun/',
'/path1/folder/fun/yay/'
)
This is what I have so far, obviously it doesn't work and it's confusing to say the least...
$a = explode('/',$path); $ii = 0; $path_array = array();
for ($i = 0; $i < sizeof($a); $i++) {
if ($a[$i]) {
$path_array[$ii] = "";
for ($n = 0; $n < $i; $n++)
{
$path_array[$ii] .= $a[$n];
}
$ii++;
}
}
file_put_contents('text.txt',serialize($path_array));
Thanks!
BTW my end goal here is to be able to run an SQL query on a table of folder paths to increment a value on a folder and all of its parents.
Maybe there's some sort of SQL operator where I could select all rows whose path is a part of the path I input? Kinda like this in reverse:
mysqli_query($mysqli,'UPDATE content_folders SET size = size+'.filesize("content/$id").' WHERE path LIKE "'.$path.'%"')

As for the PHP function - something like this would work:
function returnAllPaths ( $fullPath = '/' , Array $pathHistory = array() )
{
while ( strlen($fullPath) > 1 AND $fullPath[0] === '/' )
{
array_push($pathHistory, $fullPath);
$fullPath = preg_replace('%(.*/)[^/]+(?:/)?$%is', '$1', $fullPath);
}
array_push($pathHistory, $fullPath);
return array_reverse($pathHistory);
}

You can use this
$path = '/path1/folder/fun/yay/';
$path = explode('/',$path);
$path = array_filter($path);
$iniVal = '';
$array_paths = array();
array_push($array_paths,'/');
foreach($path as $array){
$value = $iniVal.'/'.$array.'/';
array_push($array_paths,$value);
$iniVal .= '/'.$array;
}
//print_r($array_paths);
Output would display in array such as :
Array ( [0] => / [1] => /path1/ [2] => /path1/folder/ [3] => /path1/folder/fun/ [4] => /path1/folder/fun/yay/ )
same as
array (
'/',
'/path1/',
'/path1/folder/',
'/path1/folder/fun/',
'/path1/folder/fun/yay/'
)
DEMO : PHP FIDDLE

Related

Associative Array concat value to another associative array

What I have here is a delete multiple file function in codeigniter. I need to merge or concat the value only of associative array. The value of both array was the file name and file extension of an image/file. I used md5 to change the name of the file.
This is my code
public function delete_files(){
$filesCount = count($_FILES['file_certificate']['name']);
$file_certificate = [];
$y = 0;
for($i = 0; $i < $filesCount; $i++){
$_FILES['file_certificates']['name'] = $_FILES['file_certificate']['name'][$i];
$_FILES['file_certificates']['type'] = $_FILES['file_certificate']['type'][$i];
$_FILES['file_certificates']['tmp_name'] = $_FILES['file_certificate']['tmp_name'][$i];
$_FILES['file_certificates']['error'] = $_FILES['file_certificate']['error'][$i];
$_FILES['file_certificates']['size'] = $_FILES['file_certificate']['size'][$i];
$oldname = $_FILES["file_certificates"]['name'];
$file_ext[] = pathinfo($oldname,PATHINFO_EXTENSION);
$file_ray[] = trim(strtolower(md5(time().$oldname)));
$result = array_combine($file_ray, $file_ext);
}
$path = FCPATH . 'uploads/certificate/';
array_map('unlink', $result);
}
Here's my array right now
enter image description here
I need it like this
Array
(
[0] => 46eced0ea722a94160d53b4abbb10381.jpg
[1] => 4f9ca54fa1daa022dc31b991a673cab7.pdf
)
And also I never try this if its works deleting a multiple file via this code
$path = FCPATH . 'uploads/certificate/'; //path file location
array_map('unlink', $result);
Thank you.
I got this done using foreach.
$path = FCPATH . 'uploads/certificate/';
$data = array();
foreach( $file_ray as $index => $code ) {
$value = $path.$code.'.'.$file_ext[$index];
$data[] = $value;
}

How can I store filename in php variable in incremented way from for Loop

Sorry for if my title is wrong.
Let me explain in detail here.
I want to store each filename in number-wise in php variable like
$image0 = filename.jpg
$image1 = filename.jpg
$image2 = filename.jpg
$image3 = filename.jpg
so on..
this filename.jpg is generate from for loop below is my code, current OP and expected OP.
$t = glob("/var/www/localhostmyproject.com/media/catalog/product/uploads/".$productnumber."/".$productnumber."*", GLOB_BRACE);
print_r($t);
for ($i = 0; $i <= 5; $i++) {
//$t =asort($t);
$proinfo = $t[$i];
$path_parts = pathinfo($proinfo);
echo $path_parts['basename'], "\n";
echo $imagename = "/uploads/".$productnumber."/".$path_parts['basename']."\n\n";
}
Current OP
Array
(
[0] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228a.jpg
[1] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228b.jpg
[2] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228c.jpg
[3] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228d.jpg
}
8573228a.jpg
/uploads/8573228/8573228a.jpg
8573228b.jpg
/uploads/8573228/8573228b.jpg
8573228c.jpg
/uploads/8573228/8573228c.jpg
8573228d.jpg
/uploads/8573228/8573228d.jpg
Expected OP
Array
(
[0] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228a.jpg
[1] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228b.jpg
[2] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228c.jpg
[3] => /var/www/localhostmyproject.com/media/catalog/product/uploads/8573228/8573228d.jpg
}
8573228a.jpg
/uploads/8573228/8573228a.jpg
$image0 = "/uploads/8573228/8573228a.jpg";
8573228b.jpg
/uploads/8573228/8573228b.jpg
$image1="/uploads/8573228/8573228b.jpg";
8573228c.jpg
/uploads/8573228/8573228c.jpg
$image2="/uploads/8573228/8573228c.jpg";
8573228d.jpg
/uploads/8573228/8573228d.jpg
$image3="/uploads/8573228/8573228d.jpg";
So I can use this variable $image0,$image1,$image2,$image3 in mysql query to insert data.
I tried to add this line inside for loop after echo $imagearr. But its not showing expected OP.
echo $image.$i = $path_parts[filename].$i."\n";
Please let me know how can I achieve this.
EDIT
Updated $imagearr variable name to $imagename. It might confuse to others between array $t**
You can achieve it by assigning dynamic variables (Variable Variables as Darren commented correctly) like so:
$files = ['sunset.jpg', 'moon.jpg', 'jupiter.png', 'banana.gif'];
$count = 0;
foreach($files as $file) {
${'file' . $count} = $file;
$count++;
}
// output gives you 4 strings
var_dump($file0, $file1, $file2, $file3);
Since you are already getting multiple filenames and upload directory path, and you just need to assign to an auto-increment variable.
You just need to add this :
echo $image.$i=$imagename; // it will give desired output '$image2="/uploads/8573228/8573228c.jpg";'
Your complete code :
$t = glob("/var/www/localhostmyproject.com/media/catalog/product/uploads/".$productnumber."/".$productnumber."*", GLOB_BRACE);
print_r($t);
for ($i = 0; $i <= 5; $i++) {
//$t =asort($t);
$proinfo = $t[$i];
$path_parts = pathinfo($proinfo);
echo $path_parts['basename'], "\n";
echo $imagename= "/uploads/".$productnumber."/".$path_parts['basename']."\n\n";
echo $image.$i = $imagename; // it will give desired output '$image2="/uploads/8573228/8573228c.jpg";'
}
try this example:
<?php
$array = array("variable1" => "value1","variable2" => "value2", "variable3" => "value3");
extract($array);
var_dump($variable1);
var_dump($variable2);
var_dump($variable3);
?>
output:
string(6) "value1" string(6) "value2" string(6) "value3"
In your case the following code should work:
$t = glob("/var/www/localhostmyproject.com/media/catalog/product/uploads/".$productnumber."/".$productnumber."*", GLOB_BRACE);
$images = array();
for ($i = 0; $i <= 5; $i++) {
$proinfo = $t[$i];
$path_parts = pathinfo($proinfo);
$imagename = "/uploads/".$productnumber."/".$path_parts['basename'];
$images['image'.$i] = $imagename;
}
extract($images);
var_dump($image0);
var_dump($image1);
var_dump($image2);
var_dump($image3);
var_dump($image4);
var_dump($image5);
?>
Put this in your code, you can get output:
echo $imagearr = "/uploads/".$productnumber."/".$path_parts['basename']."\n\n";
echo $image.$i=$imagearr;

Remove specific parameters from a URL using PHP

So I'm attempting to remove specific parameters from the URL query string that are predefined in an array. Here's what I have so far:
<?php
// Construct the current page URL
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = 'http://' . $host . $script . '?' . $params;
// Store all URL parameters into an array (HOST, PATH, QUERY, etc)
$url_params = array();
$url_params = parse_url($currentUrl);
// Create an array to store just the query string, breaking them apart
$params_array = explode('&', $url_params['query']);
// Array holding URL parameters that we want to remove
$params_to_remove = array("param1", "param2", "param3", "param4", "param5");
$location = 0;
// Loop through and remove parameters found in PARAMS_TO_REMOVE array
for($x = 0; $x < count($params_to_remove); $x++) {
if(in_array($params_to_remove[$x], $params_array)) {
$location = array_search($params_to_remove[$x], $params_array);
unset($params_array[$location]);
}
}
// Print array after unwanted parameters were removed
print_r($params_array);
echo '<br /><br />';
// Construct a new array holding only the parameters that we want
$clean_params_array = array();
for($z = 0; $z < count($params_array); $z++) {
if($params_array[$z] != '') array_push($clean_params_array, $params_array[$z]);
}
// Print clean array
print_r($clean_params_array);
echo '<br />';
// Construct the new URL
// If there are paramters remaining in URL reconstruct them
if(count($clean_params_array) > 0) {
$final_url = 'http://www.example.com' . $url_params['path'] . '?';
for($y = 0; $y < count($clean_params_array); $y++) {
$final_url .= $clean_params_array[$y] . '&';
}
// Trim off the final ampersand
$final_url = substr($final_url, 0, -1);
}
// No parameters in final URL
else $final_url = 'http://www.example.com' . $url_params['path'];
// Print final URL
echo '<br />' . $final_url;
?>
Here's the output:
Using http://www.example.com/test.php?apple&banana&orange&param1&strawberry&param2&pineapple
Array ( [0] => apple [1] => banana [2] => orange [4] => strawberry [6] => pineapple )
Array ( [0] => apple [1] => banana [2] => orange [3] => strawberry )
http://www.example.com/test.php?apple&banana&orange&strawberry
As you can see I'm losing the last parameter. I also feel as if I'm being too verbose...where am I going wrong?
$new_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?".implode("&",array_diff(explode("&",$_SERVER['QUERY_STRING']),Array("param1","param2","param3","param4","param5")));
One-liner ;)
Although you'd probably be better off taking that Array(...) out of there and defining it as a variable beforehand, so it's easier to read.
<?php
/**
* generateURL()
*
* Sprava URL adresy
*
* #author stenley <stenley#webdev.sk>
* #version 1.4
*/
function generateURL() {
$GET = $_GET;
$QUERY_STRING = '';
$SCRIPT_NAME = substr(strrchr($_SERVER["SCRIPT_NAME"],"/"),1);
$num_args = func_num_args();
if($num_args>0 && $num_args%2==0) {
$args = func_get_args();
foreach($args as $index => $paramName) {
$paramName = trim($paramName);
if($index%2==0 && !empty($paramName)) {
$paramValue = trim($args[$index+1]);
if(array_key_exists($paramName, $GET) && empty($paramValue)) {
unset($GET[$paramName]);
} elseif(!empty($paramValue)) {
$GET[$paramName] = $paramValue;
}
}
}
}
foreach($GET as $param => $value) {
$QUERY_STRING .= $param."=".$value."&";
}
return $SCRIPT_NAME.((empty($QUERY_STRING)) ? '' : "?".substr($QUERY_STRING,0,-5));
}
?>
here is great function for managing URL address. usage is easy. here are some examples in Slovak language. but I think you will understand code samples. or I will translate it for you
sorry for my english
Part of the answer is in this line:
Array ( [0] => apple [1] => banana [2] => orange [4] => strawberry [6] => pineapple )
Note that $params_array[5] does not exist. Yet you try to read $params_array[5] when $z==5
(In your while loop you go through values $z = 0; => $z < 6; (count($params_array))
You can use Kolink's solution, or use a foreach loop to go through all the values:
foreach($params_array as $param) {
if($param != '') array_push($clean_params_array, $param);
}

Using func_get_args to edit an array

I wish to use a function with an arbitrary number of arguments to edit an array. The code I have so far is:
function setProperty()
{
$numargs = func_num_args();
$arglist = func_get_args();
$toedit = array();
for ($i = 0; $i < $numargs-1; $i++)
{
$toedit[] = $arglist[$i];
}
$array[] = $arglist[$numargs-1];
}
The idea of the code being I can do the following:
setProperty('array', '2nd-depth', '3rd', 'value1');
setProperty('array', 'something', 'x', 'value2');
setProperty('Another value','value3');
Resulting in the following array:
Array
(
[array] => Array
(
[2nd-depth] => Array
(
[3rd] => value1
)
[something] => Array
(
[x] => value2
)
)
[Another Value] => value3
)
The issue I believe is with the line:
$toedit[] = $arglist[$i];
What does this line need to be to achieve the required functionality?
Cheers,
You need to walk the path to the destination before storing the new value. You can do this with a reference:
function setProperty() {
$numargs = func_num_args();
if ($numargs < 2) return false; // not enough arguments
$arglist = func_get_args();
// reference for array walk
$ar = &$array;
// walk the array to the destination
for ($i=0; $i<$numargs-1; $i++) {
$key = $arglist[$i];
// create array if not already existing
if (!isset($ar[$key])) $ar[$key] = array();
// update array reference
$ar = &$ar[$key];
}
// add value
$ar = $arglist[$numargs-1];
}
But the question where this $array should be stored still remains.
class foo {
private $storage;
function setProperty()
{
$arglist = func_get_args();
if(count($argslist) < 2) return false;
$target = &$this->storage;
while($current = array_shift($arglist)){
if(count($arglist)==1){
$target[$current] = array_shift($arglist);
break;
}
if(!isset($target[$current])) $target[$current] = array();
$target = &$target[$current];
}
}
}
Try using foreach to loop through your array first. Then to handle children, you pass it to a child function that will grab everything.
I also recommend using the function sizeof() to determine how big your arrays are first, so you'll know your upper bounds.

PHP Dynamically adding dimensions to an array using for loop

Here is my dilemma and thank you in advance!
I am trying to create a variable variable or something of the sort for a dynamic associative array and having a hell of a time figuring out how to do this. I am creating a file explorer so I am using the directories as the keys in the array.
Example:
I need to get this so I can assign it values
$dir_list['root']['folder1']['folder2'] = value;
so I was thinking of doing something along these lines...
if ( $handle2 = #opendir( $theDir.'/'.$file ))
{
$tmp_dir_url = explode($theDir);
for ( $k = 1; $k < sizeof ( $tmp_dir_url ); $k++ )
{
$dir_list [ $dir_array [ sizeof ( $dir_array ) - 1 ] ][$tmp_dir_url[$k]]
}
this is where I get stuck, I need to dynamically append a new dimension to the array durring each iteration through the for loop...but i have NO CLUE how
I would use a recursive approach like this:
function read_dir_recursive( $dir ) {
$results = array( 'subdirs' => array(), 'files' => array() );
foreach( scandir( $dir ) as $item ) {
// skip . & ..
if ( preg_match( '/^\.\.?$/', $item ) )
continue;
$full = "$dir/$item";
if ( is_dir( $full ) )
$results['subdirs'][$item] = scan_dir_recursive( $full );
else
$results['files'][] = $item;
}
}
The code is untested as I have no PHP here to try it out.
Cheers,haggi
You can freely put an array into array cell, effectively adding 1 dimension for necessary directories only.
I.e.
$a['x'] = 'text';
$a['y'] = new array('q', 'w');
print($a['x']);
print($a['y']['q']);
How about this? This will stack array values into multiple dimensions.
$keys = array(
'year',
'make',
'model',
'submodel',
);
$array = array();
print_r(array_concatenate($array, $keys));
function array_concatenate($array, $keys){
if(count($keys) === 0){
return $array;
}
$key = array_shift($keys);
$array[$key] = array();
$array[$key] = array_concatenate($array[$key], $keys);
return $array;
}
In my case, I knew what i wanted $keys to contain. I used it to take the place of:
if(isset($array[$key0]) && isset($array[$key0][$key1] && isset($array[$key0][$key1][$key2])){
// do this
}
Cheers.

Categories