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 )
Related
I have 10 images which is stored as an array.
Also I have a foreach which generate me 10 items.
My goal is to add random image from this array to each of my item that is generated by foreach, furthermore images shouldn't be duplicated.
For ex.:
1 item - img1.jpg;
2 item - img3.jpg;
3 item - img9.jpg...
etc.
<?php
$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');
$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
foreach ($rss->channel->item as $item) {
foreach ($images as $image) {
echo $image."<br/>"."<br/>";
}
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
}
?>
This code returns me random images for items but sometimes they are duplicated.
Is it possible to make it within PHP?
like #jeroen said you only need to shuffle the array and the array initialization should be outside the foreach!
$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg',
'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
foreach ($images as $image) {
print $image;
}
Applying this to your case :
<?php
$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');
$images = array('img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg');
shuffle ($images);
$i = 0;
foreach ($rss->channel->item $item) {
echo $images[$i]."<br/>"."<br/>";
echo $item->title."<br/>";
echo $item->link."<br/>";
echo $item->pubDate."<br/>";
$i++;
}
?>
I am developing a search engine with vector space Model. I successfully computed tf-idf with associative array data already define in code. Now I want that data should be come from directory where I have a folders and in each folder there is a number of text files with dummy data. I have tried alot but stuck at 1 point using glob function because I want all .txt files as key and its contents as value in foreach loop of glob function.... Below is my code.
Tf-idf With Associative Array Data
$collection = array(
1 => 'this string is a short string but a good string',
2 => 'this one isn\'t quite like the rest but is here',
3 => 'this is a different short string that\' not as short'
);
$dictionary = array();
$docCount = array();
foreach($collection as $docID => $doc) {
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
$temp = ('docCount' => $docCount, 'dictionary' => $dictionary);
As you see in 1st foreach loop is that $DocID is key and $doc is its contents(value) of collection array. But I don't know how to implement exact same thing when files read from directory. See code below..
Tf-idf With .txt Files and its contents read from directory
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $file) {
$file_handle = fopen($file, "r");
//echo $file;
$dictionary = array();
$docCount = array();
foreach($file as $docID=> $value) {
echo $value;
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
}
$temp = array('docCount' => $docCount, 'dictionary' => $dictionary);
This gives me error on 1st foreach loop that invalid arugument supplied for foreach loop. As I mentioned earlier I want .txt files as a key and its contents as a value in 1st foreach loop. But I got this error Can anybody please Tell me how to do this.. Thanks in advance..
If you want to treat the entire file as one value, you can use file_get_contents() to read the file into a string:
$dictionary = array();
$docCount = array();
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $docID) {
$value = file_get_contents($docID);
...
}
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);
i want so replace something in a array, but the array isn´t sorted. So maybe you know how i can fix the problem.
I´ve a array with a few of this element.
<media type="image" id="image5" label="book5.jpg" group="image" source="list2/Schuh2.jpg" url="image5/0.jpg" icon="image5/0.jpg"/>
How can i sort the array by the value of lable? so that first i get for example from
Lables:
book3
book4
book2
-->
book2
book3
book4
i hope you know what i mean :D thank you ;-)
$books = array('book3', 'book4', 'book2');
sort($books);
or
$books = array('label1' =>'book5.jpg',
'label2' => 'book4.jpg', 'label3' => 'book3.jpeg');
asort($books); // sorts by value (ascending)
hope this helps!
Hack
foreach($a as $k => $media) {
$parts = explode(' ',$media);
foreach($parts as $part) {
$kv = explode('=', $part);
if ($kv[0] == 'label') {
$a[$kv[1]] = $media;
unset($a[$k]);
}
}
}
ksort($a);
or look at usort() which let you use your own comparison function
Assuming unique book#.jpg images you could do something like ...
<?php
$sortedArray = array();
foreach ($unsortedArray as $item ) {
$sortedArray[explode('.', explode('label="book', $item)[1])[0]] = $item;
}
ksort($sortedArray);
foreach ($sortedArray as $item ) {
echo $item;
}
?>
I did not test this.
UPDATE:
Someone else's suggestion to use usort() is a good one. Something like this ...
<?php
function compareElements($a, $b) {
$aNum = explode('.', explode('label="book', $a)[1])[0];
$aNum = explode('.', explode('label="book', $b)[1])[0];
return ($aNum < $bNum) ? -1 : 1;
}
usort($arrayOfElements, "compareElements");
foreach ($arrayOfElements as $element) {
echo $element;
}
?>
The Problem was, that i can´t sorte bei the one value ['id'] so i has create me one array with all the Informations, and a second only with the ['id'] of the pictures.
Input and load the XML-File.
$mashTemplateFile = 'C:\Users\...\test.xml';
$mashTemplate = simplexml_load_file($mashTemplateFile);
$mash = $mashTemplate->mash;
declare the arry's
$imageArrayMedTemp = array();
$imageArrayMedID = array();
$imageArrayMed = array();
put all the information from the media in the array $imageArrayMedTemp and only the ['id']into the array $imageArrayMedID.
foreach ($mash->media as $med) {
if ($med['type'] == 'image') {
array_push($imageArrayMedTemp , $med);
array_push($imageArrayMedID , $med['id']);
}
now i sort the array with the ['id']'s
natsort($imageArrayMedID);
after sorting i will put the information from the array $imageArrayMedTemp into a new array $imageArrayMed, storing by when the key of both is the same.
foreach ($imageArrayMedID as $key1 => $value1) {
foreach ($imageArrayMedTemp as $key2 => $value2) {
if($key1 == $key2){
array_push($imageArrayMed,$value2);
}
}
}
I had an array which contained lines of a file that I had to process, each element of the array was a line of the file. After processing I implode the file, write it out and use it.
When I tried to use foreach for this, it didn't work. I had a suspicion that it was creating a copy of the element rather than referencing the element directly, so used a for loop instead, which did work.
My question is, is there some way to use a foreach loop in this scenario or when redefining elements of an array must you always use a for loop?
Example code:
$fileArray = file('blah.txt');
foreach ($fileArray as $thisLine) {
if ( condition ) {
$thisLine = "changed state";
}
}
$newFileArray = implode('',$fileArray);
Didn't work vs:
$fileArray = file('blah.txt');
for ($x=0;$x<count($fileArray);$x++) {
if ( condition ) {
$fileArray[$x] = "changed state";
}
}
$newFileArray = implode('',$fileArray);
Which worked fine.
$fileArray = file('blah.txt');
foreach ($fileArray as $key => $thisLine) {
if ( condition ) {
$fileArray[$key] = "changed state";
}
}
$newFileArray = implode('',$fileArray);
or passing by reference directly:
$fileArray = file('blah.txt');
foreach ($fileArray as &$thisLine) {
if ( condition ) {
$thisLine = "changed state";
}
}
$newFileArray = implode('',$fileArray);
In your first example, you're altering a copy of a string. $thisLine is not a reference to the element in the array, but a copy of the array element.
In your second example, you are altering the array directly. You could use a foreach, but only if you go back to referencing the array:
foreach ($fileArray as $key => $thisLine) {
if ( condition ) {
$fileArray[$key] = "changed state";
}
}