save path and count images in mysql database - php

I'm able to scan directory of files uploaded to server via FTP
Now I want to discard the empty arrays and add path and total count of images into MySQL database. I will use that path and count of images to use them in HTML player and run these pictures as video.
Here is my code:
<?php
$path = '/home/zackpc/usr/share/zoneminder/www/events/1';
// an unsorted array of dirs & files
$files_dirs = iterator_to_array( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),RecursiveIteratorIterator::SELF_FIRST) );
echo '<html><body><pre>';
// create a new associative multi-dimensional array with dirs as keys and their files
$dirs_files = array();
foreach($files_dirs as $dir){
if(is_dir($dir) AND preg_match('/\/\.$/',$dir)){
$d = preg_replace('/\/\.$/','',$dir);
$dirs_files[$d] = array();
foreach($files_dirs as $file){
if(is_file($file) AND $d == dirname($file)){
$f = basename($file);
$dirs_files[$d][] = $f;
}
}
}
}
print_r($dirs_files);
echo '</pre></body></html>';
?>
I am getting following output:
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06/14] => Array
(
)
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06] => Array
(
)
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06/11/21/28] => Array
(
[0] => 00020-capture.jpg
[1] => 00043-capture.jpg
[2] => 00006-capture.jpg
[3] => 00008-capture.jpg
[4] => 00049-capture.jpg
[5] => 00007-capture.jpg
[6] => 00013-capture.jpg
[7] => 00025-capture.jpg
[8] => 00016-capture.jpg
[9] => 00033-capture.jpg
[10] => 00051-capture.jpg
[11] => 00014-capture.jpg
[12] => 00044-capture.jpg
[13] => 00001-capture.jpg
[14] => 00035-capture.jpg
[15] => 00039-capture.jpg
[16] => 00048-capture.jpg
[17] => 00009-capture.jpg
[18] => 00022-capture.jpg
[19] => 00034-capture.jpg
[20] => 00024-capture.jpg
[21] => 00041-capture.jpg
[22] => 00002-capture.jpg
[23] => 00029-capture.jpg
[24] => 00023-capture.jpg
[25] => 00010-capture.jpg
[26] => 00038-capture.jpg
[27] => 00003-capture.jpg
[28] => 00017-capture.jpg
[29] => 00047-capture.jpg
[30] => 00015-capture.jpg
[31] => 00012-capture.jpg
[32] => 00005-capture.jpg
)

Only loop once. Only store what you need: paths and image counts.
foreach($files_dirs as $file){
if (is_file($file)) {
$d = dirname($file);
if (!isset($dirs_files[$d])) {
$dirs_files[$d] = 0;
} else {
++$dirs_files[$d];
}
}
}
I've got to say:
I got lost in your code.
I did not test my answer, so no guarantees that it is perfect.

Related

I want all arrays data in one array in php

I want all arrays data in one array not all arrays in one array only the data of all arrays in one array without any other array in php. I have tried to do too many things but still don't work for me.
I also tried
json_encode
with
preg_match
But still don't work for me.
Here is my code
function fetchHashtags($getData){
$body = $getData;
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
}
Output
Array
(
[0] => #Residência
[1] => #architecture
[2] => #casanaserra
[3] => #mountainhouse
[4] => #interiores
[5] => #decoration
[6] => #casanaserra
[7] => #casadecampo
[8] => #construção
[9] => #exterior
[10] => #rustico
[11] => #arpuro
[12] => #home
[13] => #riodejaneiro
[14] => #construir
[15] => #casasincriveis
[16] => #outdoor
[17] => #arquiteto
[18] => #casasincriveis
[19] => #montanhas
[20] => #archdaily
[21] => #architecturelovers
[22] => #arqlovers
[23] => #arqlove
[24] => #homedesign
[25] => #arquiteturaedecoração
)
Array
(
[0] => #We
[1] => #ascaspenvswheaton
)
Array
(
[0] => #شجریان_بشنویم...
[1] => #۰
[2] => #شجریان_بشنویم
[3] => #_
[4] => #شجریانیها
[5] => #همایون_شجریان
[6] => #مژگان_شجریان
[7] => #پرویزمشکاتیان
[8] => #موزیک
[9] => #سهراب_پورناظری
[10] => #محمدرضا_شجریان
[11] => #موزیک_ویدیو
[12] => #ایران
[13] => #ترانه_ماندگار
[14] => #تصنیف
[15] => #آهنگ_ایرانی
[16] => #هنر
[17] => #موسیقی_ایرانی
[18] => #شعروشاعری
[19] => #موسیقی_سنتی_ایران
[20] => #آواز_سنتی
[21] => #قدیمیها
[22] => #دلشدگان
[23] => #دلنشین
[24] => #سینما
[25] => #homayoun_shajarian
[26] => #music
[27] => #mohamadrezashajarian
[28] => #home
[29] => #iran
[30] => #shajarian
)
And one more thing i also want to remove some data that don't look like hashtags.
for example:
Array
(
[0] => #Residência
[1] => architecture // This should be removed
[2] => #casanaserra
[3] => mountainhouse // This also should be removed
[4] => #interiores
)
As you can see from my code you can use array_merge for merge arrays then use array_filter for filter value without # or other rules you need:
$array = [['1', '#2', '3', '#4'], ['5', '#6']];
$flatArray = array_merge(...$array);
$filteredArray = array_filter($flatArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
print_r($filteredArray);
Result:
Array (
[1] => #2
[3] => #4
[5] => #6 )
Reference:
array_merge
array_filter
str_contains
After seeing your code and the context of the situation I changed things:
Instead of use explode i used preg_split for split \n and space;
Delete array_map because you don't need it.
$array = ["
My name is Faraz shaikh i am a php developer and this my #instagram profile.Check out my #merge and my #packages with new #hashtags
#chinese #art #colors #home #harmory #peace #handmade #paintings #etsy
", "
My name is Hunain shaikh i am a php developer and this my #Facebook profile.Check out my #Berge and my #Hackages with new #tags
#english #Kite #colours #me #memory #pee #made #paints #etsafsy
"];
function fetchHashtags($getData) { // This Functions takes out the hashtags from the string and put it in to arrays.
$body = $getData;
$hashtag_set = [];
$array = preg_split('/[\s]+/', $body);
$mapArray = array_map(function($a) {
return str_replace(' ', '', $a);
}, $array);
$filteredArray = array_filter($mapArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
return $filteredArray;
}
$recentNumberOfPosts = 1;
$zeroPost = 0; //Get Post from 0 to recentNumberOfPosts | NOTE: default = 4
$finalArr = [];
while ($zeroPost <= $recentNumberOfPosts) {
// fetchHashtags($hashtagRecent['data'][$zeroPost]['caption']);
$finalArr[] = fetchHashtags($array[$zeroPost]);
$zeroPost++;
}
print_r(array_merge(...$finalArr));
Fiddle

Remove elements with dot in their path doesnt work

I need to remove all elements that contains dot in array that i receive fron ftp_nlist(), this is how i do that:
$connection = ftp_connect($host);
if(!$connection){
echo "Can't connect to $host ($login:$password)\n";
#print_r(error_get_last());
ftp_close($connection);
exit();
}
ftp_login($connection, $login, $password);
ftp_pasv($connection, TRUE);
$files_list = ftp_nlist($connection, $path);
print_r($files_list);
for($i = 0; $i< count($files_list); $i++){
if( strstr($files_list[$i], '.') ){
unset($files_list[$i]);
}
}
print_r($files_list);
echo 'Ok';
However it works strange
Array
(
[0] => /httpdocs/favicon.ico
[1] => /httpdocs/mobile.html
[2] => /httpdocs/g
[3] => /httpdocs/index.html
[4] => /httpdocs/.
[5] => /httpdocs/member.html
[6] => /httpdocs/sitemap.xml
[7] => /httpdocs/animated_favicon1.gif
[8] => /httpdocs/rakuten.html
[9] => /httpdocs/y_key_8866d9fb86f18b30.html
[10] => /httpdocs/robots.txt
[11] => /httpdocs/..
[12] => /httpdocs/bbs.html
[13] => /httpdocs/version.php
[14] => /httpdocs/css
[15] => /httpdocs/nas
[16] => /httpdocs/googlee7e5921970ceb672.html
[17] => /httpdocs/about.html
[18] => /httpdocs/images
)
Array
(
[2] => /httpdocs/g
[10] => /httpdocs/robots.txt
[11] => /httpdocs/..
[12] => /httpdocs/bbs.html
[13] => /httpdocs/version.php
[14] => /httpdocs/css
[15] => /httpdocs/nas
[16] => /httpdocs/googlee7e5921970ceb672.html
[17] => /httpdocs/about.html
[18] => /httpdocs/images
)
Ok
As you can see not all elements with dots was removed. I can't see clear reason why.
Every time you unset() an array element the count() in the condition is decreased by 1. So instead of using count($files_list); in the condition (this is evaluated each iteration), set it first so it doesn't change:
$count = count($files_list);
for($i = 0; $i < $count; $i++){
if(strpos($files_list[$i], '.') !== false){
unset($files_list[$i]);
}
}
I would prefer foreach():
foreach($files_list as $key => $file){
if(strpos($file, '.') !== false){
unset($files_list[$key]);
}
}
Also notice that strpos() is better suited here.

scandir() scan by increasing number

I want to scan a directory and add all the file-names to an array in ascending order (numeric, no letters). What appears to be happening is scandir() is sorting them by highest value of the first number and not the whole number. I need to take into account missing text files, so if 9.txt was missing, 10.txt would take its place (no empty spot in array).
Here is the code:
<?php
$array=array();
$int = 1;
$holder=scandir("/postexamples/");
krsort($holder);
foreach($holder as $x)
{
if(!is_dir($x)){
$array[$int]=$x;
$int++;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
print_r($array);
?>
Which outputs the array:
Array ( [1] => 9.txt [2] => 8.txt [3] => 7.txt [4] => 6.txt [5] => 5.txt [6] => 4.txt [7] => 3.txt [8] => 20.txt [9] => 2.txt [10] => 19.txt [11] => 18.txt [12] => 17.txt [13] => 16.txt [14] => 15.txt [15] => 14.txt [16] => 13.txt [17] => 12.txt [18] => 11.txt [19] => 10.txt [20] => 1.txt )
Is there a better (and preferably working) way to do this? I need it to be like [1] => 1.txt [2] => 2.txt
EDIT:
I need the array to appear like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 17.txt [18] => 18.txt [19] => 19.txt [20] => 20.txt )
And if one file (for example, 17.txt) was missing, it would look like this:
Array ( [1] => 1.txt [2] => 2.txt [3] => 3.txt [4] => 4.txt [5] => 5.txt [6] => 6.txt [7] => 7.txt [8] => 8.txt [9] => 9.txt [10] => 10.txt [11] => 11.txt [12] => 12.txt [13] => 13.txt [14] => 14.txt [15] => 15.txt [16] => 16.txt [17] => 18.txt [18] => 19.txt [19] => 20.txt )
You need to do a natural sort to get the files in the correct order (20.txt, 10.txt, 2.txt, 1.txt). The function for doing this is natsort.
$sortPath = 'postexamples/';
$files = array();
foreach (scandir($sortPath) as $file) {
if (is_file("$sortPath/$file")) {
$files[] = $file;
}
}
echo PHP_EOL . PHP_EOL . "Final array: " , PHP_EOL;
natsort($files);
$files = array_values($files); // re-key array
print_r($files);
Result
Final array:
Array
(
[0] => 1.txt
[1] => 2.txt
[2] => 4.txt
[3] => 10.txt
[4] => 20.txt
)
Id do it like this.
$files = array_diff(scandir("/postexamples/"), array('.', '..' ));
$array = array();
foreach($files as $file){
if(!is_dir($file)){
$array[]=$file;
}
}
sort($array, SORT_NUMERIC);
You may have to use usort, if it doesn't do the numbers right. Also if you are on php >= 5.4 you may be able to use,
scandir("/postexamples/", SCANDIR_SORT_ASCENDING );
But I haven't tried it. Using sort with numeric flag ( don't forget it's just an array like any other )
$a = Array ( '9.txt', '8.txt', '7.txt', '6.txt', '10.txt', '1.txt');
echo "<pre>";
var_export($a);
echo "<br>";
sort($a, SORT_NUMERIC);
var_export($a);
Result
array (
0 => '9.txt',
1 => '8.txt',
2 => '7.txt',
3 => '6.txt',
4 => '10.txt',
5 => '1.txt',
)
array (
0 => '1.txt',
1 => '6.txt',
2 => '7.txt',
3 => '8.txt',
4 => '9.txt',
5 => '10.txt',
)
So essentially sort($a, SORT_NUMERIC);
Try this ,i hope this will help you:
$ar=array();
$g=scandir("/postexamples/");
krsort($g)
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else $ar[]=$x;
}
print_r(sort($ar));

PHP Array Contain string

i create a method that will read a file with the application/octet type and here are some of the code.
Raw data :
GTHHS;MEKID Interface;5496;2012-07-20;
NM1;081;IN1;980898989;2001-01-15;Mr;Gaf;Uhkil;Uhkil,Gaf;PRI;Gaf
$contents = file_get_contents($tmp_filename);
$stringContents = explode(";", $contents);
Now it gives me this output :
Array
(
[0] => GTHHS
[1] => MEKID Interface
[2] => 5496
[3] => 2012-07-20
NM1
[4] => 081
[5] => IN1
[6] => 980898989
[7] => 2001-01-15
[8] => Mr
[9] => Gaf
[10] => Uhkil
[11] => Uhkil,Gaf
[12] => PRI
[13] => Gaf
PR1
[14] => 081
[15] => IN1
[16] => 20730089
[17] => 7 The Schooner
[18] => Auhaas
[19] => Huuula Ave
[20] =>
[21] => Kishma
PR2
[22] => 081
[23] => IN1
[24] => 232323233
[25] => 400006
[26] => HGD
[27] => M
[28] => M
[29] => 2007-10-16
[30] => 1976-03-31
);
How can i make the NM1, PR1 as the head of array like this :
Array (
[NM1] = array(
[0] => GTHHS
[1] => MEKID Interface
[2] => 5496
[3] => 2012-07-20
)
);
I am planning also to make the inner array [0]-[3] as json.
If you explode the contents by \n you have each line starting with that identifier. If you then just explode by ; in that line and add it as a sub array, you got it like you want.
This actually looks like a plain old CSV file with your ifentifier in line one. If so, try something like this:
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE)
{
$key = array_shift($row);
$data[$key] = $row;
}
fclose($handle);
}
echo json_encode($data);
http://php.net/manual/en/function.str-getcsv.php

Remove items from S3 objects array in php

I have an array like this:
Array
(
[0] => Accounts.csv
[1] => Book1.xlsx
[2] => Documents/
[3] => Documents/AdbWinApi.dll
[4] => Documents/AdbWinUsbApi.dll
[5] => Documents/adb.exe
[6] => Documents/boot.img
[7] => Documents/fastboot.exe
[8] => Documents/side_banner.jpg
[9] => Documents/source.properties
[10] => File Organization.docx
[11] => How to Manage Risks.docx
[12] => How to Trade Forex.docx
[13] => Ken Doc - Galad Letter Head.pdf
[14] => Ken Header.png
[15] => MX_2004_fwmx_2004_en.exe
[16] => xx.docx
[17] => asmack-master.zip
[18] => ca5rmhx7l4-Human Heart 2.7z
[19] => evasi0n7.exe
[20] => ken header.pdf
[21] => sp42471.exe
)
and I would like it to return an array like below;
Array
(
[0] => Accounts.csv
[1] => Book1.xlsx
[2] => Documents
[3] => File Organization.docx
[4] => How to Manage Risks.docx
[5] => How to Trade Forex.docx
[6] => Ken Doc - Galad Letter Head.pdf
[7] => Ken Header.png
[8] => MX_2004_fwmx_2004_en.exe
[9] => xx.docx
[10] => asmack-master.zip
[11] => ca5rmhx7l4-Human Heart 2.7z
[12] => evasi0n7.exe
[13] => ken header.pdf
[14] => sp42471.exe
)
I am using the code below;
{
private function listFiles($bucket = null , $prefix = null) {
$ls = S3::getBucket($bucket, $prefix);
if(!empty($ls)) {
foreach($ls as $l) {
$fname = str_replace($prefix,"",$l['name']);
if(!empty($fname)) {
$rv[] = $fname;
}
}
}
if(!empty($rv)) {
return $rv;
}
}
}
What changes can I make to my code to get the above results. I am using Donovan Schönknecht Amazon S3 library for codeigniter.
You could use a foreach
$newarr=array();
foreach($entries as $v)
{
if(strpos($v,'/')!==false)
{
$v=explode('/',$v);
if(isset($v[1]) && strlen($v[1])>0){}else{$newarr[]=$v[0];}
}
else { $newarr[]=$v;}
}
print_r($newarr);
Working Demo
You can overwrite the elements with $array[3] = ""; e.g. Then u have empty array-elements and then you could use a function like this:
function empty_array($array){
foreach($array as $ar => $value) {
if($value == '') {
unset($array[$ar]);
}
}
return $array;
}
$new_array = emtpy_array($old_array);

Categories