Make a Unique PHP Array based on a section of the value? - php

I am working on a WordPress site where the client has uploaded thousands of photos to Flickr and now want me to move them all back into WordPress and associate them with there proper posts.
Even though there are thousands of images, there is really only about 50 unique images, all the other versions are the same image but uploaded to a different location on Flickr or a slightly different size or name.
In helping me track down all the unique images, based on a list like below, that part I have highlighted, I need to pull every record into a PHP array, the catch is the part I have highlighted, is what I want to make sure is UNIQUE among all records in the array.
Any help in taking an existing PHP ARRAy that has every record and making the array only show unique values based on that part of the Value string?
Is this a Regular Expressions use case?
If it used Regex or similar I think a pattern it could look for is /4485116555_ / followed by 10 digits and then followed up with a _
Appreciate any help in getting me 1 step closer to my goal, this is just 1 piece of the big puzzle.
http://farm5.static.flickr.com/4042/4485116555_19cc0eaa85.jpg
http://farm3.static.flickr.com/2703/4485767454_77476dbdd0.jpg
http://farm5.static.flickr.com/4008/4485116637_ff085b0ab2.jpg
http://farm5.static.flickr.com/4002/4485766896_af83d349c4.jpg
http://farm5.static.flickr.com/4037/4485766950_50d5739344.jpg
http://farm3.static.flickr.com/2785/4485116905_1fa0e2ea6c.jpg
http://farm5.static.flickr.com/4052/4704387613_77542dac2e.jpg
http://farm3.static.flickr.com/2734/4485767622_7b04c3bd3e.jpg
http://farm5.static.flickr.com/4037/4485767292_1a37fe6c57.jpg
http://farm5.static.flickr.com/4038/4485116955_f9c47672c3.jpg
http://farm5.static.flickr.com/4051/4485115681_6d7419a00b.jpg
http://farm3.static.flickr.com/2753/4485116095_30161a56bb.jpg
http://farm5.static.flickr.com/4123/4831194968_3977dff9dc.jpg
http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg
http://farm3.static.flickr.com/2091/4515081466_43cd1624ce.jpg
http://farm3.static.flickr.com/2684/4485766664_3bb9dd9c80_m.jpg
http://farm5.static.flickr.com/4010/4485115557_a38aac0e1f.jpg
http://farm5.static.flickr.com/4055/4485115633_19e6e92276.jpg
http://farm5.static.flickr.com/4045/4485766710_08691e99ed_m.jpg
http://farm5.static.flickr.com/4024/4485115521_9ab2a33d53_m.jpg
http://farm5.static.flickr.com/4048/4505577820_81ce080f2a_t.jpg
http://farm6.static.flickr.com/5294/5389182894_920a54ce97_m.jpg
http://farm5.static.flickr.com/4152/5073487038_5bdb9e3cbc_t.jpg
http://farm5.static.flickr.com/4024/4485115401_67a8957509_m.jpg
http://farm5.static.flickr.com/4062/4485766842_2209843592_m.jpg

$ids = array(); // Where we will keep our unique list of IDs
$lines = array(/* your list of URLs here */);
foreach ($lines as $line) {
preg_match(
'|^http://[A-Za-z0-9\\.]+/[0-9]+/([0-9]+)_[a-f0-9]+.*\\.jpg$|',
'http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg',
$matches
);
echo $matches[1]; // 4538941056
$ids[] = $matches[1]; // Push that into the IDs array
}
$ids = array_unique($ids);
print_r($ids);

Use this code to get your ID Portion
$url = 'Your image url';
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);
$id = substr($end,0,9);
And then run array_unique() to get the unique values.

Related

Filter a php array to only elements that have a matching value to $name in $data

I have a php script getting all folders in a posts folder and making them into a list.
I have a $postinfo_str variable assigned to a json file for each folder which I am using to store post date and category/tag info etc in.
I also have a $pagetitle variable assigned to a title.php include file for each folder. So say I am on a "June 2018" archive page, the text in that file will be "June 2018". If I am on say a "Tutorials" category page, that will be the text in the title.php.
In the json file, I have:
{
"Arraysortdate": "YYYYMMDD",
"Month": "Month YYYY",
"Category": ["cat1", "cat2", "etc"]
}
I am ordering the array newest to oldest using krsort with Arraysortdate as key.
How do I filter the array using $pagetitle as input, finding if there is a match in $postinfo_str, and if there isn't, remove that folder from the array?
All I can seem to find regarding array sorting is where the info in the $pageinfo_str is basically the array and so by that, the $title is the input and the output is the matching text from the $postinfo_str, whereas I want the output to be the folders that only have the matching text in the $postinfo_str to what the input ($pagetitle) is.
Here is my code I have.. Keep in mind this is flat file, I do not want a database to achieve this. See comments if you want an explaination.
<?php
$BASE_PATH = '/path/to/public_html';
// initial array containing the dirs
$dirs = glob($BASE_PATH.'/testblog/*/posts/*', GLOB_ONLYDIR);
// new array with date as key
$dirinfo_arr = [];
foreach ($dirs as $cdir) {
// get current page title from file
$pagetitle = file_get_contents("includes/title.php");
// get date & post info from file
$dirinfo_str = file_get_contents("$cdir/includes/post-info.json");
$dirinfo = json_decode($dirinfo_str, TRUE);
// add current directory to the info array
$dirinfo['dir'] = $cdir;
// add current dir to new array where date is the key
$dirinfo_arr[$dirinfo['Arraysortdate']] = $dirinfo;
}
// now we sort the new array
krsort($dirinfo_arr);
foreach($dirinfo_arr as $key=>$dir) {
$dirpath = $dir['dir'];
$dirpath = str_replace('/path/to/public_html/', '', $dirpath);
?>
<!--HTML HERE SUCH AS--!>
TEXT <br>
<?php
};
?>
I have difficulties following your problem description. Your code example is slightly confusing. It appears to load the same global includes/title.php for each directory. Meaning, the value of $pagetitle should be the same every iteration. If this is intended, you should probably move that line right outside the loop. If the file contains actual php code, you should probably use
$pagetitle = include 'includes/title.php';
or something similar. If it doesn't, you should probably name it title.txt. If it is not one global file, you should probably add the path to the file_get_contents/include as well. (However, why wouldn't you just add the title in the json struct?)
I'm under the assumption that this happened by accident when trying to provide a minimal code example (?) ... In any case, my answer won't be the perfect answer, but it hopefully can be adapted once understood ;o)
If you only want elements in your array, that fulfill certain properties, you have essentially two choices:
don't put those element in (mostly your code)
foreach ($dirs as $cdir) {
// get current page title from file
$pagetitle = file_get_contents("includes/title.php");
// get date & post info from file
$dirinfo_str = file_get_contents("$cdir/includes/post-info.json");
$dirinfo = json_decode($dirinfo_str, TRUE);
// add current directory to the info array
$dirinfo['dir'] = $cdir;
// add current dir to new array where date is the key
// ------------ NEW --------------
$filtercat = 'cat1';
if(!in_array($filtercat, $dirinfo['Category'])) {
continue;
}
// -------------------------------
$dirinfo_arr[$dirinfo['Arraysortdate']] = $dirinfo;
array_filter the array afterwards, by providing a anonymous function
// ----- before cycling through $dirinfo_arr for output
$filtercat = 'cat1';
$filterfunc = function($dirinfo) use ($filtercat) {
return in_array($filtercat, $dirinfo['Category']));
}
$dirinfo_arr = array_filter($dirinfo_arr, $filterfunc);
you should read up about anonymous functions and how you provide local vars to them, to ease the pain. maybe your use case is bettersuited for array_reduce, which is similar, except you can determine the output of your "filter".
$new = array_filter($array, $func), is just a fancy way of writing:
$new = [];
foreach($array as $key => $value) {
if($func($value)) {
$new[$key] = $value;
}
}
update 1
in my code samples, you could replace in_array($filtercat, $dirinfo['Category']) with in_array($pagetitle, $dirinfo) - if you want to match on anything that's in the json-struct (base level) - or with ($pagetitle == $dirinfo['Month']) if you just want to match the month.
update 2
I understand, that you're probably just starting with php or even programming, so the concept of some "huge database" may be frightening. But tbh, the filesystem is - from a certain point of view - a database as well. However, it usually is quite slow in comparison, it also doesn't provide many features.
In the long run, I would strongly suggest using a database. If you don't like the idea of putting your data in "some database server", use sqlite. However, there is a learning curve involved, if you never had to deal with databases before. In the long run it will be time worth spending, because it simplifys so many things.

Extract a full substring from a partial substring (needle)

As you can see below, I'm attempting to extract the complete substring of an exploded array by using just a few characters to match the substring.
$keyword = array('Four Wheel', 'Power', 'Trailer');
function customSearch($keyword, $featurelistarray){
$key = ''; //possibly reset output
foreach($featurelistarray as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
$termname = $key;
}
}
}
The array ($featurelistarray) comprises vehicle options, four wheel drive, four wheel disc brakes, power windows, power door locks, floor mats, trailer tow package, and many many more.
The point is to list all the options for a given category, and using the $keyword array to define the category.
I would also like to alphabetize the results. Thank you for the help!
To further explain, the $featurelistarray is exploded from a CSV field. The CSV field has a long length of options listed.
$featurelist=$csvdata['Options'];
$featurelistarray=explode(',',$featurelist);
$termname = $featurelistarray[0];
As you can see, $termname is assigned the first position of the exploded array. This was the original code for these features, but I need more control for $termname.
It seems to me you are trying to make database operations without database. I'd suggest to transform input into some kind of database.

How to find #hashtags in strings using Laravel 4.1?

I am currently trying to filter through an Input string to find the single hashtags that a user wants to be displayed with his photo. However, I am currently getting inserts in my database that are not correct.
The best case scenario would be that every single hashtag is saved in a new database row with the photo id. However, I do not really know what to do to accomplish that.
$hashtag = new Hashtag;
$hashtag->photo_id = $photo->id;
$hashtag_string = Input::get('hashtags');
$hashtag_string = Str::contains($hashtag_string, '#')
$hashtag->hashtag = $hashtag_string;
$hashtag->save();
I found some functions in this cheat sheet (http://cheats.jesse-obrien.ca) but I do not get them to work properly.
Try this:
$str = $hashtag_string;
preg_match_all('/#(\w+)/', $str, $matches);
foreach ($matches[1] as $hashtag_name) {
$hashtag = Hashtag::firstOrCreate(array('hashtag' => $hashtag_name));
}
You could then, in this foreach loop, connect those hashtags to a post (or in your case a photo) or sth.

active users script, user count not working properly

i have written a script to output active users on my site....
part of this is counting unique ips in the log, as the array i use to split the lines / data unloads active users from the array list after 5 minutes.....
however the "3 online users now" count is not working properly.....
it kinda works.... when someone views a page, it says there is 1 user
lets say i view a page.... 1 visitor
then user 2 views a page .... 2 visitors
but if i then view another page, it displays 3 users.....
even though i use the same ip for both page requests....
here is my code
$data = file_get_contents('active-log.txt');
$break = "\r\n";
$lines = explode($break, $data);
foreach ($lines as $key => $value) {
$active_ip[] = $lines[$key][1];
}
$active_ip_count = array_unique($active_ip);
$active_users = (count($active_ip_count));
$active_users is the variable i use to display how many unique visitors are online at one time
thanks in advance for anyone that can help me thanks
....
EDIT
.....
here is a sample of the log saved....
1328469393|157.55.39.84|g-book
1328469398|157.55.39.84|downloads
1328469400|157.55.39.84|badger
1328469404|157.55.39.84|home
1328469408|157.55.39.84|boneyard-dogs
the first part is timestamp (to remove the line from array, if timestamp is older than 5 minutes... this works fine)
the second part is ip
third part is page viewed and the new line is created with \r\n
$lines[$key][1] is the variable for each ip in each line....
as im not exacly a php expert, when writing scripts, i test them heavily while developing, and each time i add a new line of script , i echo the data, to check its what i hope, to make sure i make no mistakes......
here is a section of code that i didnt paste as i didnt think it was necessary....
foreach($lines as $k=>$v) {
$lines[$k] = explode("|", $v); }
// echo $lines[0][0]; // now this is first array of first line .... line 2 / url would be - $lines[1][2]
this is in my code, straight after the line "$lines = explode($break, $data);" in my code
Have you looked at the output of var_dump($active_ip) after the foreach loop ends? With this setup, I'm pretty sure $lines[$key][1] is simply the first character of the line you're dealing with, so that's not going to work well for a number of reasons. What does active-log.txt look like? Does it only contain IP addresses or user names, too? If it only contains IP addresses, consider using something like this:
<?php
$data = file('active-log.txt');
$no_duplicate_ips = array_unique($data);
$active_users = (count($no_duplicate_ips));
?>
Edit:
Right, that makes sense then. Try this:
$data = file_get_contents('active-log.txt');
$break = "\r\n"; //Note that it's generally a good idea to use PHP_EOL throughout your code, for greater cross-platform compatibility
$lines = explode($break, $data);
$exploded_data = array();
$active_ips = array();
foreach($lines as $v) {
$exploded_data = explode("|", $v);
//Now check whether the timestamp is not > 5 min
if(TIMESTAMP CHECK HERE) {
//OK, this one is not too old
$active_ips[] = $exploded_data[1];
}
}
$active_ip_count = array_unique($active_ip);
$active_users = (count($active_ip_count));

Random Link PHP

EDITED
I'm trying to setup a random link at the bottom of all my pages. I'm using the code below, but want to make it so the current page is not included in the random rotation of links.
Example:
I need code to randomly select and display ONE of these links. The exception being, IF article1.php is currently being viewed, I want it to be excluded from the random selection. That way only links to OTHER articles are seen on any given article.
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
I would use array_rand with something like:
<?php
$links = array(array('url' => 'http://google.com', 'name'=>'google'),
array('url' => 'http://hotmail.com', 'name' => 'hotmail'),
array('url' => 'http://hawkee.com', 'name' => 'Hawkee'));
$num = array_rand($links);
$item = $links[$num];
printf('%s', $item['url'], $item['name'], $item['name']);
?>
Where links makes it easier to build an array. Nevertheless, I think we miss some details about how you grab your links.
What is the mean of "current page"? because the simplest way to do, is just not add the page to the array.
And the use of array_rand avoids confusion with size of array and so.
Edit: I suppose you use a database, so you may have an sql request like:
SELECT myfieldset FROM `articles` WHERE id = 'theid';
So you know the id of the current article. Now you just have to build an array with some other articles with a query like:
SELECT id FROM `articles` WHERE id NOT IN ('theid') ORDER BY RAND LIMIT 5
And build the candidate array with those results.
Each time you randomly choose a URL to display, pop it off of the array and store it in a temporary variable. Then, on the next rotation make your selection and THEN push the previously used URL back into the array.
$lastUrl = trim(file_get_contents('last_url.txt'));
while($lastUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){}
file_put_contents('last_url.txt', $randUrl);
// ...
echo $randUrl;
Ensures that on each page load, you will not receive the previous URL. This, however is just an example. You would want to incorporate file locking, exception handling (perhaps) or an entirely different storage medium (DB, etc.)
To ensure the URL is not the same as the current, this should do the trick:
// get current URL
$currentUrl = 'http://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
// randomize URLs until you get one that doesn't match the current
while($currentUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){ }
echo $randUrl;
Google "PHP get current URL", and you'll get considerably more detailed ways to capture the current URL. For example, conditions on whether or not you're use HTTPS, to append an 's' to the protocol component.
try the codes below :
$links = array(
'http://mysite.com/article1.php',
'http://mysite.com/article2.php',
'http://mysite.com/article3.php',
'http://mysite.com/article4.php',
'http://mysite.com/article5.php'
);
$currentPage = basename($_SERVER['SCRIPT_NAME']);
$count = 0;
$currentIndex = NULL;
foreach($links as $link) {
if(strpos($link, "/".$currentPage)>-1) $currentIndex = $count;
$count++;
}
if($currentIndex) {
do{
$random = mt_rand(0, sizeof($links) - 1);
} while($random==$currentIndex);
} else {
$random = mt_rand(0, sizeof($links) - 1);
}
$random_link = $links[$random];

Categories