I have a list of IDs
$Ids="1201,1240,1511,1631,1663,1666,1716,2067,2095";
and in the /imgs/ folder there are many jpg filenames related to these IDs. But there are a lot of IDs that do not have any image.
for example there are in the /imgs/
1201_73.jpg
1201_2897.jpg
1240-9834.jpg
1240-24.jpg
1511-dsc984.jpg
1511-dsc34.jpg
What I want to achieve is to find which of the IDs have images in the img folder.
Thank you
Updated
$array = array();
$foo = explode('.jpg', $images);
foreach($foo as $id) {
$digi = substr(trim($id), 0,4);
if(!in_array($digi, $array)) {
array_push($array, $digi);
echo $id . ".jpg <br/>";
$where .= "id='$digi' or ";
}
}
First, turn your string of IDs into an array.
$idsArray = explode(',', $Ids);
Now iterate through the directory, checking each file to see if it starts with the ID.
$hasImages = array();
foreach (new DirectoryIterator(__DIR__ . '/imgs') as $fileInfo) {
if ($fileInfo->isDot() || $fileInfo->isDir()) {
continue;
}
foreach ($idsArray as $id) {
if (0 === strpos($fileInfo->getBasename(), $id)) {
$hasImages[] = $id;
break;
}
}
}
$hasImages = array_unique($hasImages);
$hasImages will contain an array of IDs which have an image.
Something like this should work:
$files = glob('/imgPath/*.jpg');
$hasImage = array_unique(array_map(function($file) {
return explode('-', $file)[0];
}, $files));
$withimages= array_diff(explode($Ids), $hasImage);
Related
I'm looping through files in a directory and saving name and hash in array like so:
$localfileslist = [];
$localfiles = glob($_GET['name'].'/*');
foreach($localfiles as $localfile){
if(is_file($localfile)){
$localfilehash= hash_file('sha256', $localfile);
array_push($localfileslist,$localfile, $localfilehash);
}
}
$uniques= array_unique($localfileslist);
$dupes=array_diff_assoc($localfileslist,$aunique);
print_r($result);
Now, I'm stumped on how to proceed and finding dupes and deleting them; any help is appreciated
Basically I first store each hash and name together. Then I group that array on the hash, pushing all same hashed names to each group. Finally we can filter that grouped array only having the items with more than 1 names.
$localfileslist = [];
$localfiles = glob(DEFINE_PATH . '/*');
foreach ($localfiles as $localfile) {
if (is_file($localfile)) {
$localfilehash = hash_file('sha256', $localfile);
array_push($localfileslist, ['name' => $localfile, 'hash' => $localfilehash]);
}
}
$grouped = array_reduce($localfileslist, function ($agg, $item) {
if (!isset($agg[$item['hash']])) {
$agg[$item['hash']] = [];
}
$agg[$item['hash']][] = $item["name"];
return $agg;
}, []);
$duplicates = array_filter($grouped, function ($item) {
return count($item) > 1;
});
print_r($duplicates);
How to delete folder with images and mysql record news that does not exist?
Dont work. Why?
$resnotid = mysqli_query($db, "SELECT id FROM objects");
$idarray[] = array();
$namefolderarray[] = array();
while($rownotid = mysqli_fetch_array($resnotid)) {
$idarray[] = $rownotid['id'];
}
$dir = opendir('upload');
while($folder = readdir($dir)) {
if (is_dir('upload/'.$folder) && $folder != '.' && $folder != '..') {
$namefolderarray[] = $folder;
}
}
$delid = array_diff($namefolderarray, $idarray);
rmdir('upload/'.$delid.'/');
The method array_diff returns an array. So you have to iterate over that array.
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $delid) {
rmdir('upload/'.$delid.'/');
}
Update 1
The previous solution only works for empty folders. If you have any content in the folders you must first delete the content. This can be done with an recursive function that iterates over the contents.
function rmdir_recursively($path) {
if (is_dir($path)){
$list = glob($path.'*', GLOB_MARK);
foreach($list as $item) {
rmdir_recursively($item);
}
rmdir($path);
} else if (is_file($path)) {
unlink($path);
}
}
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
}
Update 2
To also delete the database-records without a folder you can extend the code like this:
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
$del_id_escaped = mysqli_real_escape_string($del_id);
mysqli_query($db, "DELETE FROM objects WHERE id='$del_id_escaped'");
}
I couldn't understand the multidimensional array in PHP properly. I have a CSV file having two columns as shown below:
I am trying to create an array of array, in which each key is a cataegory. However, the value of each key is an array. In this array, each key is company and value is the count of the product. See below the code:
<?php
//array contains value
function contains_value($my_array, $value_search){
foreach ($my_array as $key => $value) {
if ($value === $value_search)
return true;
}
return false;
}
//array contains key
function contains_key($my_array, $key_search){
foreach ($my_array as $key => $value) {
if ($key === $key_search)
return true;
}
return false;
}
$handle = fopen("product_list.csv", "r");
$products = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$product = explode(",", $line);
$category = $product[0];
$company = $product[1];
if (contains_key($products, $category)) {
if (contains_value($products, $company)) {
//increase the count of category by 1
$products[$category][$company] = $products[$category][$company] + 1;
} else {
//append new company with count 1
array_push($products[$category], array(
$company,
1
));
}
} else {
//initialize new company with count 1
$products[$category] = array(
$company,
1
);
}
}
fclose($handle);
}
var_dump($products);
?>
I noticed that the var_dump($products) is not showing correction information. I am expecting following kind of result:
I haven't enough reputation to reply, but I think he need counts.
To complete the answer of Alive to Die, more something like this:
if (!array_key_exists($category, $products)) {
products[$category] = [];
}
if (!array_key_exists($company, $products[$category])) {
products[$category][$company] = 0;
}
++$results[$cataegory][$company];
But cleaner ;)
Edit:
If I remember well, his first idea was this:
$products[$category][] = $company;
The code is shorter. Maybe you can combine the two ideas.
I want to remove duplicate values from array. I know to use array_unique(array) function but faced problem in foreach loop. This is not a duplicate question because I have read several questions regarding this and most of them force to use array_unique(array) function but I have no idea to use it in foreach loop. Here is my php function.
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
$listImages=$image;
echo substr($listImages, 0, -25) ."<br>"; //remove last 25 chracters
}
How to do this?
It is very complicated to remove duplicate values from array within foreach loop. Simply you can push all elements to one array and then remove the duplicates and then get values as you need. Try with following code.
$listImages=array();
$images = scandir($dir);
foreach($images as $image){
$editedImage = substr($image, 0, -25);
array_push($listImages, $editedImage);
}
$filteredList = array_unique($listImages);
foreach($filteredList as $oneitem){
echo $oneitem;
}
The example you provided could be modified as follows:
$images = scandir($dir);
$listImages=array();
foreach($images as $image) {
if (!in_array($image, $listImages)) {
$listImages[] = $image;
}
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
Now $listImages will contain no duplicates, and it will echo every image (including duplicates).
Based on #mistermartins answer:
$images = scandir($dir);
$listImages=array();
foreach($images as $image) {
//if already echo'd continue to next iteration
if (in_array($image, $listImages)) {
continue;
}
//else, add image to array and echo.
$listImages[] = $image;
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
It should be faster to use hashmaps:
$images = scandir($dir);
$listImages = array();
foreach($images as $image) {
if (!isset($listImages[$image])) {
$listImages[$image] = true;
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
}
I'm not sure if I have understood you completely. Subsequent approach worked for me in order to remove duplicate indizes from array using a foreeach loop.
$list = array("hans", "peter", "hans", "lara", "peter", "lara", "lara");
sort($list);
foreach ($list as $k => $v) {
if (isset($check)) {
if ($check === $v) {
unset($list[$k]);
}
}
$check = $v;
}
$noDuplicate = array_values($list);
print_r($noDuplicate);
gives following result:
Array ( [0] => hans [1] => lara [2] => peter )
I tried comparing 2 text files with data separated by -, in one case one file gets all data and in another case only has the data for change with the same id in this case this file it's called db_tmp.txt
The structure in both files it's this :
File txt ( the first it´s the id ) db/text.txt
1a34-Mark Jhonson
1a56-Jhon Smith
1a78-Mary Walter
The file for comparing, has for example the data for change, same id but different content - db_tmp.txt
1a56-Tom Tom
I created a function for comparing both files to detect if the same id and change exists:
<?php
$cron_file = file("db_tmp.txt");
$cron_compare = file("db/test.txt");
function cron($file_temp, $file_target)
{
for ($fte = 0; $fte < sizeof($file_temp); $fte++) {
$exp_id_tmp = explode("-", $file_temp[$fte]);
$cr_temp[] = "" . $exp_id_tmp[0] . "";
}
for ($ftt = 0; $ftt < sizeof($file_target); $ftt++) {
$exp_id_targ = explode("-", $file_target[$ftt]);
$cr_target[] = "" . $exp_id_targ[0] . "";
}
$diff = array_diff($cr_target, $cr_temp);
$it = 0;
foreach ($diff as $diff2 => $key) {
echo $diff2;
echo "--- $key";
print "<br>";
}
}
cron($cron_file, $cron_compare);
?>
If the same id exists in tmp, i must detect the entry in the other file and change to the value of the tmp, i try but can't get this to work, the function works but not for everything, if anyone can help me, that would be perfect, because i don´t know how continue this and save.
If you want to match according to id, a simple foreach would suffice, then just check during the loop if they have the same key. Consider this example:
// sample data from file('db_text.txt');
$contents_from_text = array('1a34-Mark Jhonson','1a56-Jhon Smith', '1a87-Mary Walter');
// reformat
$text = array();
foreach($contents_from_text as $element) {
list($key, $value) = explode('-', $element);
$text[$key] = $value;
}
$tmp = array();
// sample data from file('db_tmp.txt');
$contents_from_tmp = array('1a56-Tom Tom', '1a32-Magic Johnson', '1a23-Michael Jordan', '1a34-Larry Bird');
foreach($contents_from_tmp as $element) {
list($key, $value) = explode('-', $element);
$tmp[$key] = $value;
}
// compare
foreach($tmp as $key => $value) {
foreach($text as $index => $element) {
if($key == $index) {
$tmp[$key] = $element;
}
}
}
$contents_from_tmp = $tmp;
print_r($contents_from_tmp);
Sample Output