I'm confusing :S with this script...This script working if there are some file, and I will get the echo like:
|test1.txt|test2.txt|test3.txt|test4.txt
the problem is when doesn't exist any file, the php will get an error:
Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6
Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8
is possible to make a function who look if there are the file, if not, get an echo like "no file found" without error?
<?php
$User = $_GET['User'];
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
//print date("d M. Y:|H:i:s |", $timestamp);
print '|'. basename($path) .'' . "" . '';
}
?>
the last thing, I don't understand how works the order for the data creation of file... if I create a new file, the new file will the last of the string...how I can invert the order??
Thank you very much :)
The solution is simple: You need to initialize your variable $docs before you use it to an empty variable like this:
$docs = array(); // <-- create array $docs before use...
foreach (glob("Myuser/$User/*.txt") as $path) {
$docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys
To let the function output an error message instead, if there are no such files, you can simply count the number of array elements using count($docs) and check if it is 0 like this:
if (count($docs) == 0) {
echo "no file found";
}
You can use arsort() instead of asort() to get the latest file as first.
Related
so I am working with a multidimensional array.
For example, the output data I am trying to get is like this:
[[element 1],[element 2], [element 3]]
This is my PHP code (minus the entire prepared statement which goes above the bind ((not included as this is working fine)):
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
if($vessel_fcm_new != $vessel_fcm_old){
$data = array($vessel_fcm_new, $vessel_fcm_old);
}
if ($vessel_name_new != $vessel_name_old){
array_push($data, $vessel_name_new, $vessel_name_old);
}
$data_return[] = $data;
}
echo json_encode($data_return);
Basically, the code is initiated to iterate through each database row, and if the condition is met it will build an array, and add the array to the array object. So the outcome would look like this, if the matching conditions are met:
[[row 1], [row2], [row3]]
However, I am getting this error:
Warning: array_push() expects parameter 1 to be array, null given in C:\htdocs\alterajax.php on line 16
But I am specifying the array already, or at least I think I am ($data).
This is also what I see as the output:
[null,null,null,null,null,["FCMjgis","fFH465","Smokey","GIIGE"]]
I'm sure this is just something minor, but I would appreciate some guidance if you can assist. Thank you in advance!
Like I said, just initialize your variable or test if its initialized using isset
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
if($vessel_fcm_new != $vessel_fcm_old){
$data = array($vessel_fcm_new, $vessel_fcm_old);
}
if (isset($data) && $vessel_name_new != $vessel_name_old){
array_push($data, $vessel_name_new, $vessel_name_old);
$data_return[] = $data;
}
}
echo json_encode($data_return);
Make sure to initialize your variables!
In this case, all I needed to do was initialize the $data array. I did this by placing $data = []; (or also $data = array();) on the line above the while loop
After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:
Array
(
[ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1
)
Then I try to access any element and I fail:
echo $record['ix'];
Notice: Undefined index: ix
echo next($record); // return nothing!
Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)
<?php
require "..\CsvImporter.lib.php";
$importer = new CsvImporter('my_route\\my.csv',true);
while($records = $importer->get())
{
// debug
print_r($records[0]);
exit;
foreach ($records as $record)
{
\\ ..
}
}
And my screen output is
Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )
My data:
ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1
So how is possible I'm unable to access any key ?
As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use
Example code \
$i=0;
while($records = $importer->get())
{
if($i>0) //skip first row it is heading
{
$data = explode(',',$records);
print_r($data);
// now `$data[0]` contains `ix` value for your first csv row and so on
}
$i++;
}
I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value
Now, I see the problem I can do it easy:
$f = 'file.csv';
$separator = ',';
$file = file_get_contents($f);
// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));
Thanks all!
Hello here's what I'm trying to achieve. I have this code to scan specific directory and store all sub-directories within array. But when I output it with foreach, only one value is outputted.My code:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz)); }
<?php foreach ($dirname as $slozka) {
echo <<<dir
$("a[rel='$slozka']").colorbox({maxWidth: "90%", maxHeight: "90%", opacity: ".5"}).;
dir;
} ?>
<?php echo '}'.PHP_EOL ?>
The output is always just one line with sub-directory
Any ideas?
This loop appears incorrect:
foreach(glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname = array (basename($sloz));
}
I assume you are trying to build an array of matches. But in this loop you are just assigning the value to variable $dirname in each case.
You are then trying to iterate over a non-iterable value, which triggers a PHP Warning: Invalid argument supplied for foreach()..., although I assume you do not have warnings enabled since you did not mention this.
Try the following:
$dirname = [];
foreach (glob($directories.'*', GLOB_ONLYDIR) as $sloz) {
$dirname[] = basename($sloz);
}
Then you can foreach over your array of $dirname values.
I would like to pass in an array that contains a list of directories to scan. I want to iterate over each directory and push its content into another array that I will print out, but for some reason my code is not working. The directories exist and the path is correct. I think it has something to do with how I'm using foreach.
These are the errors I'm getting:
Notice: Undefined index: C:\Users\john\Desktop\files\images\ in
C:\xampp\htdocs\test.php on line 6
Warning: scandir(): Directory name cannot be empty in
C:\xampp\htdocs\test.php on line 6
This is the code:
function test($dir = []) {
foreach($dir as $bar) {
$list = [];
array_push($list, scandir($dir[$bar]));
}
print_r($list);
}
test(["C:\Users\john\Desktop\files\images\\", "C:\Users\john\Desktop\files\images\autumn\\"]);
If anyone can think of a simpler way to do this, please don't hesitate to tell me.
You're on the right track. There are a few changes you need to make though.
function test($dir = []) {
$list = [];
foreach($dir as $bar) {
$list[] = scandir($bar);
}
print_r($list);
}
As noted by #BrianPoole you need to move the $list out of the foreach loop. By having it in the loop, the array is reset with each iteration, resulting in the final array having one element.
In addition, the foreach loop as explained above by #TimCooper does not operate the same as in JavaScript. If you really want to access the keys, you can use the following syntax:
foreach($dir as $key => $bar)
You would then use either $dir[$key] or $bar to access the directory value.
Finally, array_push is an additional function call that in your case is not needed. By simply adding [] PHP will push the new value onto the end of the array.
function test($dir) {
// DEFINE LIST OUT SIDE OF LOOP
$list = array();
// Run checks
if(count($dir) > 0) {
// Loop Through Directory
foreach($dir as $directory) {
// Push into list
array_push($list, array("scanned"=>$directory, "contents" => scandir($directory)));
}
}else {
// If no directories are passed return array with error
$list = array(
"error" => 1,
"message" => "No directories where passed into test()",
);
}
print_r($list);
}
This is how I would do it. It provides a couple checks and sets up the data so you can se it a bit more clear.
I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.