Search and remove from result? - php

I got this result and i want extraction first image from folder clear just the first
Example of the result
http://i.i.com.com/cnwk.1d/i/tim/2012/07/12/Les_Horribles_Cernettes_in_1992_620x350.jpg
http://i.i.com.com/cnwk.1d/i/tim/2012/07/03/IBM-350-publicdomain_220x157.jpg
http://cbsdigitalmedia.112.2o7.net/b/ss/cbscbsnewscomatlantisuat/1/H.21--NS.png
http://dw.com.com/clear/c.gif
http://i.i.com.com/cnwk.1d/i/tim/2012/07/03/IBM-350-publicdomain_220x157.jpg
http://dw.com.com/clear/test2.gif
http://cbsdigitalmedia.112.2o7.net/b/ss/cbscbsnewscomatlantisuat/1/H.21--NS.png
http://dw.com.com/clear/test.gif
The image i want
http://dw.com.com/clear/c.gif

OK, so I was actually quite intrigued by your question.. So I came up with a little something...
$firstFile;
//This is the array with your URL values
$imgUrls[0] = "http://i.i.com.com/cnwk.1d/i/tim/2012/07/12/Les_Horribles_Cernettes_in_1992_620x350.jpg";
$imgUrls[1] = "http://i.i.com.com/cnwk.1d/i/tim/2012/07/03/IBM-350-publicdomain_220x157.jpg";
$imgUrls[2] = "http://cbsdigitalmedia.112.2o7.net/b/ss/cbscbsnewscomatlantisuat/1/H.21--NS.png";
$imgUrls[3] = "http://dw.com.com/clear/c.gif";
$imgUrls[4] = "http://i.i.com.com/cnwk.1d/i/tim/2012/07/03/IBM-350-publicdomain_220x157.jpg";
$imgUrls[5] = "http://dw.com.com/clear/test2.gif";
$imgUrls[6] = "http://cbsdigitalmedia.112.2o7.net/b/ss/cbscbsnewscomatlantisuat/1/H.21--NS.png";
$imgUrls[7] = "http://dw.com.com/clear/test.gif";
//This foreach loop goes through the array and checks the containing directory
foreach($imgUrls as $value){
$urlParts = explode("/",$value);
if($urlParts[count($urlParts)-2] == "clear"){
$firstFile = $value;
break;
}
}
//After setting $firstFile as the Image URL, echo it out.
echo $firstFile;

Related

PHP Looping through JSON data without knowing the numbers of data

I am trying to get all images from an image API. It returns a maximum of 500 result at a time and if the result has a next_page field, then I have to grab the value of that field and add it to the URL. The code should continue looping until that field is absent. I used the following code to grab the first two pages:
$key = true;
$link = 'https://url.com/dhj/?prefix=images&type=download';
$json = file_get_contents($link);
$data = json_decode($json, true);
$dataArray = array();
foreach ($data["images"] as $r)
{
array_push($dataArray, array($r["id"], $r["image"]));
}
while($key)
{
if($data["next_page"])
{
$key=true;
$link2 = "https://url.com/dhj/?prefix=images&type=download&next_page=" . $data[$next_page];
$json2 = file_get_contents($link2);
$data2 = json_decode($json2, true);
foreach ($data2["images"] as $r2)
{
array_push($dataArray, array($r2["id"], $r2["image"]));
}
}
else
{
$key=false;
}
}
This should fetch 2000 records but is only fetching 1000 records, so it appears the loop is not working as expected.
So your problem is that you are only fetching twice. The second time, you never check $data2 for a next page, so everything stops. You do not want to keep going like this, or you will need $data3, $data4, etc.
A do/while loop is similar to a while loop, except that it always runs at least once. The condition is evaluated at the end of the loop instead of the beginning. You can use that behaviour to ensure you always get the first page of data, and then use the condition to check if you should keep getting more.
$page = "";
do {
$link = "https://url.com/dhj/?prefix=images&type=download&next_page=$page";
$json = file_get_contents($link);
$data = json_decode($json, true);
foreach ($data["images"] as $r) {
$dataArray[] = [$r["id"], $r["image"]];
}
$page = $data["next_page"] ?? "";
} while ($page);
Note I've got rid of your array_push() call. This is rarely used in PHP because the $var[] syntax is less verbose and doesn't require predeclaration of the array. Likewise, calls to array() have long been replaced by use of array literal syntax.
The expression $page = $data["next_page"] ?? "" uses the null coalesce operator, and is identical to:
if (isset($data["next_page"])) {
$page = $data["next_page"];
} else {
$page = "";
}

Need to copy a specific text generated on page to a string in PHP

I made a PHP script which is generating result "https://secure.nmi.com/api/v2/three-step/44505010"
44505010 is a number that changes every time. I need to create a $reference string which I can assign that dynamic number to $reference.
I tried this code but it doesn't seem to work. Can someone help me out?
$reference = getStr($page, 'https://secure.nmi.com/api/v2/three-step/','');
Thanks
Try this:
<?php
function getUrlPart($url = '') {
$urlarr = parse_url($url);
$split = explode('/', $urlarr['path']);
$c = 1;
while($split[count($split)-$c] == ''){
$c++;
}
return var_export($split[count($split)-$c], true);
}
$url = 'https://secure.nmi.com/api/v2/three-step/44505010//';
echo getUrlPart($url);
In this method you can get the route name at any depth, even with query parameters at the end.
$yourUrl = 'https://secure.nmi.com/api/v2/three-step/44505010';
$reference = (int) explode('/', $yourUrl)[6];
This assumes the general URL format does not change.

PHP getting all files into array issue

I have an small piece of PHP code that needs to put every file in the current directory into an array.
I have done this by making reading the dir with glob() and when it meets another dir it will loop.
My code I have as of now:
<?php
$find = '*';
$result = array();
function find($find)
{
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
find($zoek);
}
}
return $result;
}
print_r(find($find));
?>
When I execute the code the echo print exactly what I want. But the printed array doesn't give me the values I want, it only gives the values in the first dir it will come by then it seems to stop adding the value in the array.
What am I doing wrong?
You need to actually preserve the results you produce in the recursive callings to your function:
<?php
function listNodesInFolder($find) {
$result = [];
foreach (glob($find) as $entry) {
$result[] = $entry;
if (is_dir($entry)) {
$result = array_merge($result, find($entry.'/*'));
}
}
return $result;
}
print_r(find('*'));
Once on it I also fixes a few other issues with your code:
$result should be declared as an array inside your function, that that even if it does not loop you still return an array and not something undefined.
indentation and location of brackets got adjusted to general coding standards, that makes reading your code much easier for others. Get used to those standards, it pays out, you will see.
no need for an extra variable for the search pattern inside the conditional.
a speaking name for the function that tells what it actually does.
you should not name variables and functions alike ("find").
You need to add the result of find() to the array
Edit added array_merge - Cid's idea
<?php
$find = '*';
function find($find)
{
$result = array();
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
$result = array_merge($result, find($zoek));
}
}
return $result;
}
print_r(find($find));
?>

PHP - get single file based on user

I'm having trouble getting my code to work the way I want.
I'm using scandir to get all files from the directory. This gives me a list with pdf files linked to a product, but the problems comes with the posibllity of pdf files multiple languages. Like so:
1096_EN.pdf
867_PT.pdf
914_EN.pdf
914_NL.pdf
Before _ is ID and after language. And I want the user to only see one file per product.
my code looks likes this:
$files = scandir($dir);
foreach ($files as $file)
{
$exp_file = explode("_", $file);
// check file for given ID
if($exp_file[0] == $_GET['iD']){
// check file for userlanguage
if($exp_file[1] == $lang){
echo $file;
}
// check file in english
elseif($exp_file[1] == "EN"){
echo $file;
}
// return available file in other language
else{
echo $file;
}
}
}
In case of 914 and NL the code returns two files. In case of 914 and PT i only get 1 file, 914_EN.pdf and in case of 867 and NL there will be zero files.
What is the best way to filter my files and return the best matched file? I personally think the error is in the for loop, but I cant find a proper way out..
thanks
If you want to have just the single items, you should keep a backlog of which you have already processed, as the foreach loop will go from for example 914_EN.pdf to 914_NL.pdf, while the checks have already been completed for 914_EN.pdf, so when you get to 914_NL.pdf, it just reruns the checks and thinks it is okay.
if working with multiple same values, you can first cleanse the array to get what you wanted. You can take a look at this, if this what you want. Cheers!
$files = array("1096_EN.pdf", "867_PT.pdf", "914_EN.pdf", "914_NL.pdf");
$new_exp_file = array();
foreach ($files as $file) {
$exp_file = explode("_", $file);
$new_exp_file[] = $exp_file[0];
}
$new_exp_file_arr_ = array_values(array_unique($new_exp_file));
for($i = 0, $file_ctr = count($new_exp_file_arr_); $i < $file_ctr; $i++) {
if($new_exp_file_arr_[$i] == "914") {
echo $new_exp_file_arr_[$i] . "<br>";
echo "<ul>";
foreach ($files as $file) {
$exp_file = explode("_", $file);
if($new_exp_file_arr_[$i] == $exp_file[0]) {
echo "<li>" . $exp_file[1] . "</li>";
}
}
echo "</ul>";
}
}
this seems to work for me? Using a regex probably not as efficient as the above methods though.
$_GET['iD'] = 1096;
$ptn = "^((\d+)\_([a-zA-Z]+)\.([a-zA-Z]+))^";
$aFiles = array('1096_EN.pdf','867_PT.pdf','914_EN.pdf','914_NL.pdf');
$lang = "EN";
foreach ($aFiles as $sFileName)
{
preg_match($ptn, $sFileName, $aFileParts);
var_dump($aFileParts);
// check file for given ID
if($aFileParts[2] == $_GET['iD']){
// check file for userlanguage
if(strtolower($aFileParts[3]) == strtolower($lang)){
echo $sFileName;
break;
}
// return available file in other language
else{
echo $sFileName;
}
}
}
I've solved my problem by the following:
if(glob($_GET['iD']."_".$_GET['t']."*.pdf"))
{
$file = glob($_GET['iD']."_".$_GET['t']."*.pdf");
echo $file[0];
}
else
{
if(glob($_GET['iD']."_EN*.pdf"))
{
$file = glob($_GET['iD']."_EN*.pdf");
echo $file[0];
}
else
{
$file = glob($_GET['iD']."*.pdf");
echo $file[0];
}
}
No more looping, just checking for different files with wildcards. Works like a charm. I.m.o. much cleaner with larger lists of files..

add/combine json array to array in JSON file php

I have been trying to solve this problem for the better part of two days with no success. I am trying combine/add to a json array that is stored in a .json file on my server using php.
This is a short version of what I'm trying to combine.
box.json:
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}]
posted json:
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I need.
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I get. (an array inside an array)
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]
This is my code:
<?php
$sentArray = $_POST['json'];
$boxArray = file_get_contents('ajax/box.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
$json = json_encode($sentdata);
$fsize = filesize('ajax/box.json');
if ($fsize <= 5000){
if (json_encode($json) != null) { /* sanity check */
$file = fopen('ajax/box.json' ,'w+');
fwrite($file, $json);
fclose($file);
}else{
/*rest of code*/
}
?>
Please help my sanity is starting to come in to question.
here is your problem
$sentdata[] = $getdata;
use foreach
foreach($getdata as $value)
$sentdata[] = $value;
UPDATE:
but i think you need this for $sentdata not $getdata
foreach($senttdata as $value)
$getdata[] = $value;
then put $getdata to your file.
$box = json_decode(file_get_contents('ajax/box.json'));
$posted = json_decode($_POST['json']);
$merge = array_merge ((array)$box,(array)$posted);
Casting (array) prevent error if $box or $posted become null or false, it will be an empty array
Instead of this:
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
Try:
$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);
By using array_merge you're combining the arrays into one instead of adding one array as a value into the other.
Note that I changed the name of your resulting data - try to avoid variables with the same name and different capitalization, it will make things much easier to understand (for you and for future developers supporting your code).
Cheers

Categories