This question already has answers here:
scandir - sort numeric filenames
(3 answers)
Closed 2 years ago.
I am building a website and I am having some issues with directories, files and with the php scandir() function. What i have to do is to take images from a folder and then dynamically create a gallery with the these images. Each image has a number in front of its name (ex. 1,nameimg.jpg; 2,nameimg.jpg ecc.) and the problem is that the array returned from scandir() isn't sorted or, better, it is sorted until i have 9 images but when i try to reach the number ten or above it keeps returning this:
Array (
[0] => 1,ADR19604.jpg
[1] => 10,_MG_9690.jpg
[2] => 11,_MG_9785.jpg
[3] => 2,_MG_9685.jpg
[4] => 3,_MG_9732.jpg
[5] => 4,_MG_9750.jpg
[6] => 5,_MG_9759.jpg
[7] => 6,ADR19551.jpg
[8] => 7,ADR19586.jpg
[9] => 8,ADR19604.jpg
[10] => 9,ADR19608.jpg
)
What can i do this sort the array correctly, even when there are more than 9 files?
If all of your files have a UNIQUE number in front of them, you can resort the array really easily like so:
<?php
$imgData = [
'1,ADR19604.jpg',
'10,_MG_9690.jpg',
'11,_MG_9785.jpg',
'2,_MG_9685.jpg',
'3,_MG_9732.jpg',
'4,_MG_9750.jpg',
'5,_MG_9759.jpg',
'6,ADR19551.jpg',
'7,ADR19586.jpg',
'8,ADR19604.jpg',
'9,ADR19608.jpg',
];
$formattedArray = [];
foreach ($imgData as $key => $value) {
//Extract the identifier
$pieces = explode(',', $value);
$number = $pieces[0];
$imgName = $pieces[1];
$formattedArray[$number] = $imgName;
}
var_dump($formattedArray);
If you have more than one image, with the same identifying number:
// Uses $imgData from first example.
$formattedArray = [];
foreach ($imgData as $key => $value) {
//Extract the identifier
$pieces = explode(',', $value);
$number = $pieces[0];
$imgName = $pieces[1];
$formattedArray[$number][] = $imgName;
}
var_dump($formattedArray);
If you're pulling the data from a database, you could also consider using separating the product ID to it's own column for better ordering.
Related
This question already has answers here:
How to extract data from csv file in PHP
(13 answers)
Closed 1 year ago.
Apologies if this question is close to others. I have tried every solution to accomplish something simple with nothing but failure. :-(
I want the keys from array one to be assigned as keys to array two.
$demos_keys = array_keys($demos);
//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys + $csvdata; simply adds the arrays but doesn't assign keys
So then I tried to loop through each element to assign the keys manually - to no avail!
foreach ($csvdata as $row){
for($i = 0; $i<count($demo_keys); $i++) {
$csvdata[$demo_keys[$i]]=$row[$i];
}
}
demos_keys:
lastname":"lastname","email":"email","d1":"phone","d2":"status"
csvdata:
"Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r",etc.
I feel the csvdata array is wonky somehow. Every thing say it is an array with about 1000 rows, but the carriage return at the end of the last element is troubling me. I thought I'd deal with it later.
What else can I try!? Thank you all for any contributions!
It looks like each row of your CSV data has not been parsed into separate variables (are you reading it from a file using fgets or file instead of fgetcsv?). So you need to split it before you can combine it with the keys from $demos_keys. Something like this should work:
$demos_keys = array("lastname","email","d1","d2");
$csvdata = array("Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r");
$result = array();
foreach ($csvdata as $row) {
$data = explode(',', trim($row));
$result[] = array_combine($demos_keys, $data);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[lastname] => Dryer
[email] => fdryer#email.com
[d1] => Backfield
[d2] => North
)
[1] => Array
(
[lastname] => Harris
[email] => fharris#email.com
[d1] => Corp
[d2] => South
)
)
Demo on 3v4l.org
This question already has answers here:
PHP - Replace data within multidimensional array, specific key
(2 answers)
How to replace a value in multidimensional array - PHP
(1 answer)
Closed 3 years ago.
I have this kind of array:
Array
(
[0] => Array
(
[title] => Personal
[closeable] => 1
[visible] => 1
)
[1] => Array
(
[title] => My contracts
[closeable] => 1
[visible] => 1
)
[2] => Array
(
[title] => Info
[closeable] => 1
[visible] => 1
)
)
I need to replace one word in the array - My contracts for something else.
My contracts will be always there, but the order may change, so I must check for the exact name and replace it.
I tried it via str_replace($value, $replacement, $array);
also via
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
and finally:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
Nothing worked. So how can I replace that one word?
foreach ($ar as &$item) {
if ($item['title'] === 'My contracts') {
$item['title'] = 'Some new value';
// if you're sure that record will be met ONCE
// you can add `break;` to stop looping
}
}
If you want to use array_walk, you can approach as
$stringToFind = 'My contracts';
$stringToReplace = 'REPLACMENT';
array_walk($arr, function(&$v,$k) use ($stringToFind,$stringToReplace){
($v['title'] == $stringToFind) ? ($v['title'] = $stringToReplace) : '';
});
This question already has answers here:
find the filename from a string with php
(3 answers)
Closed 7 years ago.
I have a .csv file which I have converted into an array $outputData. The 6th $data[6] element of each array contains an image file path, e.g.
http://images.pleaserusa.com/pic/unique.image.jpg
I need to remove the the filepath http://images.pleaserusa.com/pic/ of each image and leave just the image name itself, e.g.
unique.image.jpg
I have looked on here and Google and tried to use preg_match() and str* functions, but I'm not really getting anywhere with it.
Rizer123 I have placed the "basename" function but can't get it to replace inside the element . i can only get it to echo/print outside the array / i have placed the code below and an excerpt array out put below .
domina-456-b.jpgArray
(
[0] => DOM456/B
[1] => 6" Lace-Up Pump W/ D-Ring&Ribbon Lace
[2] => Devious
[3] => Single Soles
[4] => DOMINA-456
[5] => Blk Pat
[6] => http://images.pleaserusa.com/pic/domina-456-b.jpg
[7] => 5-15
)
domina-460-b.jpgArray
(
[0] => DOM460/B
[1] => 6" Oxford Lace Up Pump
[2] => Devious
[3] => Single Soles
[4] => DOMINA-460
[5] => Blk Pat
[6] => http://images.pleaserusa.com/pic/domina-460-b.jpg
[7] => 5-16
)
<?php
$input = 'Parser/Inv_item.csv';
$output = 'hd_inv_items.csv';
if (false !== ($ih = fopen($input, 'r'))) {
$oh = fopen($output, 'w');
header('Content-Type: text/plain');
while (false !== ($data = fgetcsv($ih))) {
// this is where you build your new row
$outputData = array($data[0], $data[1], $data[2], $data[3], $data[5],$data[6], $data[9], $data[8]);
$path = $data[9];
$name = basename($path); // $name == '1.jpg'
print_r($name);
print_r($outputData);
//fputcsv($oh, $outputData);
}
fclose($ih);
fclose($oh);
}
?>
As you can see the image file path is still in the array and the basename result is printing outside of the array . How do i fix this issue
Regards Biwwabong
No need for explosions or string manipulations for this, a simple basename() should suffice:
$path = 'http://images.pleaserusa.com/pic/unique.image.jpg';
echo basename($path);
output:
unique.image.jpg
pathinfo() would work as well:
echo pathinfo($path, PATHINFO_BASENAME);
I always do this with explode()
$url = "http://images.pleaserusa.com/pic/unique.image.jpg";
$parts = explode("/",$url);
$pic = $parts[count($parts)-1];
You are welcome ;-)
I've searched around and I found some similar questions asked, but none that really help me (as my PHP abilities aren't quite enough to figure it out). I'm thinking that my question will be simple enough to answer, as the similar questions I found were solved with one or two lines of code. So, here goes!
I have a bit of code that searches the contents of a given directory, and provides the files in an array. This specific directory only has .JPG image files named like this:
Shot01.jpg
Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can use the results directly in an tag to be displayed on a site I'm building. However, I'm having a little trouble as I want to limit my array to not return items if they contain "_tn", so I can use the thumbnail that links to the full size image. I had thought about just not having thumbnails and resizing the images to make the PHP easier for me to do, but that feels like giving up to me. So, does anyone know how I can do this? Here's the code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so I'm also going to want to limit the results from the array to be a random 3 results. But, if that's too much to ask, I can figure that part out on my own I believe.
So there's no confusion, I want to completely remove the items from the array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!
<?php
function filtertn($var)
{
return(!strpos($var,'_tn'));
}
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
);
$filesarray=array_filter($array, "filtertn");
print_r($filesarray);
?>
Just use stripos() function to check if filename contains _tn string. If not, add to array.
Use this
<?php
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
)
foreach($array as $k=>$filename):
if(strpos($filename,"_tn")){
unset($array[$k]);
}
endforeach;
Prnt_r($array);
//OutPut will be you new array removed all name related _tn files
$array = Array(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
?>
I can't understand what is the problem? Is it required to add "_tn" to array? Just check "_tn" existence and don't add this element to result array.
Try strpos() to know if filename contains string "_tn" or not.. if not then add filename to array
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
$filesarray = array();
foreach($array as $fileObject):
// Check - string contains "_tn" substring or not
if(!strpos($fileObject->getPathname(), "_tn")){
// Check - value already exists in array or not
if(!in_array($fileObject->getPathname(), $filesarray)){
$filesarray[] = $fileObject->getPathname();
}
}
endforeach;
print_r($filesarray);
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example