Remove elements with dot in their path doesnt work - php

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.

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

save path and count images in mysql database

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.

Fastest way to reach a url via PHP

What is the fastest way to reach a URL with PHP without any output needed?
I did a testing on the code below by using file_get_contents and CURL, but the result inconstant and very close to each other.
function abtest()
{
$arr_to_return = array();
$t = microtime(true);
file_get_contents('http://127.0.0.1/test.html');
$e = microtime(true);
$arr_to_return['file_get_contents'] = $e-$t;
$t = microtime(true);
$handle = curl_init('http://127.0.0.1/test.html');
curl_setopt($handle, CURLOPT_NOBODY, TRUE);
curl_exec($handle);
curl_close($handle);
$e = microtime(true);
$arr_to_return['curl'] = $e-$t;
return $arr_to_return;
}
$limit = 20;
$count = 0;
$result = array();
$filegetcontents = 0;
$curl = 0;
do{
$test = abtest();
$result['file_get_contents'][] = $test['file_get_contents'];
$filegetcontents += $test['file_get_contents'];
$result['curl'][] = $test['curl'];
$curl += $test['curl'];
$count++;
} while ( $count < $limit);
echo '<pre>';
print_r($result);
echo '</pre>';
echo 'Average: file_get_contents ('.($filegetcontents/$limit).') curl ('.($curl/$limit).')';
As per suggested, I put it into a function and loop 20 times on localhost with direct IP.
Result as below:
Array
(
[file_get_contents] => Array
(
[0] => 0.0055451393127441
[1] => 0.0056819915771484
[2] => 0.0056838989257812
[3] => 0.014945983886719
[4] => 0.014636993408203
[5] => 0.014842987060547
[6] => 0.0053179264068604
[7] => 0.015022039413452
[8] => 0.014861106872559
[9] => 0.015033960342407
[10] => 0.015429973602295
[11] => 0.015249013900757
[12] => 0.01471996307373
[13] => 0.015311002731323
[14] => 0.0054020881652832
[15] => 0.015032052993774
[16] => 0.0051870346069336
[17] => 0.014680147171021
[18] => 0.014776945114136
[19] => 0.015046119689941
)
[curl] => Array
(
[0] => 0.0013649463653564
[1] => 0.0017318725585938
[2] => 0.0013041496276855
[3] => 0.0013928413391113
[4] => 0.0013279914855957
[5] => 0.0013871192932129
[6] => 0.011061906814575
[7] => 0.0013771057128906
[8] => 0.010823011398315
[9] => 0.0015439987182617
[10] => 0.0015928745269775
[11] => 0.0014979839324951
[12] => 0.0016429424285889
[13] => 0.011864900588989
[14] => 0.0015189647674561
[15] => 0.0014710426330566
[16] => 0.0014939308166504
[17] => 0.001460075378418
[18] => 0.011038064956665
[19] => 0.010931015014648
)
)
Average: file_get_contents (0.012120318412781) curl (0.0038913369178772)
Seems result of CURL is better than file_get_contents most of the time. Any faster way to do this other than above?

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);

fgetcsv not working for yahoo stock csv? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i wanted to read the csv file i load from yahoo that includes some stock data. 2 days before i used this code:
$ticker_url="";
for($i=0;$i<200;$i++){
if($i==199){
// $ticker=array with all 200 stock ticker....
$ticker_url=$ticker_url.$ticker[$i];
}else{
$ticker_url=$ticker_url.$ticker[$i]."+";
}
}
$url="http://finance.yahoo.com/d/quotes.csv?s='$ticker_url'&f=snxab2l1va2p2opm3m4ghd1t1=.csv";
$filehandle=fopen($url,"r");
while(!feof($filehandle)){
$line=fgetcsv($filehandle,1024);
echo $line[0]."<br/>";
}
fclose($filehandle);
But now it doesn't work anymore. There is no problem with $url works fine. but reading the lines with fgetcsv hust loops 6 times and got no elemnts in it...
pls help.
$ticker = array('GOOG', 'ACE', 'FDX'); // test tickers
$ticker_url = '';
$count = count($ticker);
for ($i = 0; $i < $count; $i++)
{
$ticker_url .= (0 === $i)
? $ticker[$i]
: '+' . $ticker[$i];
}
$url = 'http://finance.yahoo.com/d/quotes.csv?s=' . $ticker_url . '&f=snxab2l1va2p2opm3m4ghd1t1=.csv';
ini_set('auto_detect_line_endings', TRUE);
if (($handle = fopen($url, 'r')) !== FALSE)
{
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
print_r($data);
}
fclose($handle);
}
Outputs:
Array
(
[0] => GOOG
[1] => Google Inc.
[2] => NasdaqNM
[3] => 719.55
[4] => 719.55
[5] => 719.49
[6] => 912426
[7] => 2583440
[8] => +1.71%
[9] => 720.03
[10] => 707.38
[11] => 688.697
[12] => 669.546
[13] => 718.00
[14] => 727.00
[15] => 1/2/2013
[16] => 10:27am
[17] => GOOG
[18] => GOOG
[19] => +12.11 - +1.71%
[20] => GOOG
[21] => 912426
)
Array
(
[0] => ACE
[1] => Ace Limited Commo
[2] => NYSE
[3] => N/A
[4] => 80.91
[5] => 80.91
[6] => 279438
[7] => 1476060
[8] => +1.39%
[9] => 81.20
[10] => 79.80
[11] => 79.4015
[12] => 76.014
[13] => 80.56
[14] => 81.58
[15] => 1/2/2013
[16] => 10:28am
[17] => ACE
[18] => ACE
[19] => +1.11 - +1.39%
[20] => ACE
[21] => 279438
)
Array
(
[0] => FDX
[1] => FedEx Corporation
[2] => NYSE
[3] => N/A
[4] => 94.59
[5] => 94.59
[6] => 594530
[7] => 2092040
[8] => +3.13%
[9] => 93.46
[10] => 91.72
[11] => 89.7738
[12] => 89.4001
[13] => 93.37
[14] => 95.19
[15] => 1/2/2013
[16] => 10:28am
[17] => FDX
[18] => FDX
[19] => +2.87 - +3.13%
[20] => FDX
[21] => 594530
)
Alternative method since above does not seem to work on your server:
$ticker_url = '';
$count = count($ticker);
for ($i = 0; $i < $count; $i++)
{
$ticker_url .= (0 === $i)
? $ticker[$i]
: '+' . $ticker[$i];
}
$url = 'http://finance.yahoo.com/d/quotes.csv?s=' . $ticker_url . '&f=snxab2l1va2p2opm3m4ghd1t1=.csv';
$csv = explode("\n", file_get_contents($url));
unset($csv[count($csv) - 1]); // remove empty row
foreach ($csv as $line)
{
$data = str_getcsv($line);
print_r($data);
}
Add an echo $url; , look at the output and then ... look over the other parameters of fgetcsv : http://php.net/manual/en/function.fgetcsv.php (delimiter and enclosure).

Categories