PHP - Remove items from an array with given parameter - php

I've searched around and I found some similar questions asked, but none that really help me (as my PHP abilities aren't quite enough to figure it out). I'm thinking that my question will be simple enough to answer, as the similar questions I found were solved with one or two lines of code. So, here goes!
I have a bit of code that searches the contents of a given directory, and provides the files in an array. This specific directory only has .JPG image files named like this:
Shot01.jpg
Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can use the results directly in an tag to be displayed on a site I'm building. However, I'm having a little trouble as I want to limit my array to not return items if they contain "_tn", so I can use the thumbnail that links to the full size image. I had thought about just not having thumbnails and resizing the images to make the PHP easier for me to do, but that feels like giving up to me. So, does anyone know how I can do this? Here's the code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so I'm also going to want to limit the results from the array to be a random 3 results. But, if that's too much to ask, I can figure that part out on my own I believe.
So there's no confusion, I want to completely remove the items from the array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!

<?php
function filtertn($var)
{
return(!strpos($var,'_tn'));
}
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
);
$filesarray=array_filter($array, "filtertn");
print_r($filesarray);
?>

Just use stripos() function to check if filename contains _tn string. If not, add to array.

Use this
<?php
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
)
foreach($array as $k=>$filename):
if(strpos($filename,"_tn")){
unset($array[$k]);
}
endforeach;
Prnt_r($array);
//OutPut will be you new array removed all name related _tn files
$array = Array(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
?>

I can't understand what is the problem? Is it required to add "_tn" to array? Just check "_tn" existence and don't add this element to result array.

Try strpos() to know if filename contains string "_tn" or not.. if not then add filename to array
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
$filesarray = array();
foreach($array as $fileObject):
// Check - string contains "_tn" substring or not
if(!strpos($fileObject->getPathname(), "_tn")){
// Check - value already exists in array or not
if(!in_array($fileObject->getPathname(), $filesarray)){
$filesarray[] = $fileObject->getPathname();
}
}
endforeach;
print_r($filesarray);

Related

PHP arrays within an array - nested arrays PHP

I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:
$fields = get_field_object('slideshow');
With this code I can narrow it down to what I want to achieve:
print_r($fields[value];
By now I get this array below:
Array
(
[0] => Array
(
[videoWebm] => /wc/data/uploads/sea.webm
[videoMp4] => /wc/data/uploads/sea1.mp4
[text] => Test1
[kund] => Kund1
[link1] =>
[link2] =>
)
[1] => Array
(
[videoWebm] => /wc/data/uploads/turntable.webm
[videoMp4] => /wc/data/uploads/turntable.mp4
[text] => Test2
[kund] => Kund2
[link1] =>
[link2] =>
)
)
it can grow more - like [2] => Array, [3] => Array etc.
I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:
print_r($fields[value][0][videoWebm]);
But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...
Anyone suggestions?
Best, Niklas
You can use foreach:
foreach ($fields[value] as $field) {
$videoWebms[] = $field['videoWebm']
$videoMp4s[] = $field['videoMp4'];
}
Or as splash58 said, use array_column:
$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');
I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).
https://www.google.com/search?q=php%20foreach
To get the value from repeater use this :
$slides = get_field('slideshow');
if($slides){
foreach($slides as $slide){
echo $slide['videoWebm'];
echo $slide['text'];
echo $slide['kund]'];
echo $slide['link1'];
echo $slide['link2'];
}
}

PHP, file_get_contents, for loop, str_replace

I am quite new with PHP and I am trying to read something form an API.
At the moment I use
$homepage = file_get_contents('http://www.site.com');
echo $homepage
This returns something which looks like this:
Array
(
[0] => Array
(
[name] => myname
[user_id] => 31232
)
[1] => Array
(
[name] => anothername
[user_id] => 23534
)
)
So here is what I want: I only want to read the [name] => x and leave the rest, so I tried a for loop within str_replace, but all I got were errors.
I hope someone is able to help me
Edit:
I just saw I could set is as a json text too, it returns something like
[{"name":"myname","user_id":"31232"},{"name":"anothername","user_id":"23534"}]
Edit2: Thank you Tuga, that was exactly what I was searching for :) I can't upvote, since my reputaion is below 15, is there another way for me to show your answer helped?
$array = json_decode($homepage); will return an array, then you can loop the array containing objects and use 'name' attribute :
foreach ($array as $obj) echo $obj->name;

How to change variable names inside array php

Ok so I have been struggling with this for hours now and I cannot seem to figure out what I'm trying to do. I have an array with many percent values placed inside and I'm printing out the first 5 of them. The $percent variables are acquired through similar_text
$array=array($percent12, $percent13, $percent14,
$percent15, $percent16, $percent17,
$percent18, $percent19, $percent110,
$percent111, $percent112, $percent113,
$percent114, $percent115, $percent116,
$percent117, $percent118, $percent119,
$percent120);
print_r(array_slice($array,0,5));
and it outputs like this:
Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )
So what i'm trying to figure out here is if it's possible to print the results of my array as they are listed above. example output would look like this:
Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )
i feel like this isn't possible, but if not, is there a way to assign the
[0]=> 36.015505697169 [1]=> 2.4181626187962
...etc to output something else say like:
[web0]=> 36.015505697169 [web1] => 2.4181626187962
Please help!! It's driving me crazy!!
You need to make it an associative array:
$array=array('percent12' => $percent12,
'percent13' => $percent13,
...);
I recommend using array_combine()
Basically you're just going to setup your new array with the keys, and pass in your current array for the values, thus creating a new array with the keys you want in the right place.
Try like
$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
$newArr['web'.$i++] = $value;
}
print_r($newArr);

Reading array-like values from .INI file into PHP array? Example inside

I searched similar questions but found nothing quite did what I want.
I have a large INI file which contains basic key/value pairs on each line. Lots of the keys are basically "arrays" stored in .INI format as you'll see in the excerpt below:
# Excerpt from INI file itself...
CountryFlagsPackage=CountryFlags
bAllowBinds=False
bShowTime=False
Records[0]=14.64
Records[1]=16.33
Records[2]=11.47
Records[3]=13.26
Records[4]=16.64
Records[5]=19.34
I'm using parse_ini_string() to put the INI into an array which results in this:
# Excerpt from print_r() after parse_ini_string()
[CountryFlagsPackage] => CountryFlags
[bAllowBinds] => False
[bShowTime] => False
[Records[0]] => 14.64
[Records[1]] => 16.33
[Records[2]] => 11.47
[Records[3]] => 13.26
[Records[4]] => 16.64
[Records[5]] => 19.34
My question is: is there an elegant way to group all those "Records" entries into one PHP array? Currently - as you see above - they're just individual array items. Basically, I'm looking for the above array to become multi-dimensional.
I could use array_keys() and look for the text "Records" but that's not very elegant or re-usable.
Edit: I suppose I could use a regex to look for anything with square brackets at the end, too. Any better solutions?
I doubt there's a native way to do this, so here's what I did:
$file = parse_ini_string($ini);
foreach ($file as $key => $value) {
if (preg_match("/(\w+)\[\d+]/", $key, $matches)) {
// "Array" style key/value
$arrays[$matches[1]][] = $value;
} else {
// Standard key/value pair
$arrays[$key] = $value;
}
}
print_r($arrays);
Results in:
Array
(
[CountryFlagsPackage] => CountryFlags
[bAllowBinds] => False
[bShowTime] => False
[Records] => Array
(
[0] => 14.64
[1] => 16.33
[2] => 11.47
[3] => 13.26
[4] => 16.64
[5] => 19.34
)
)

PHP array issue

I have an Array List that I want to output like my example below. How can I achieve it in PHP?
Array List:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
Want to output like this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
Thanks,
steamboy
You can use array_combine() and pass two copies of your original array:
$new_list = array_combine($list, $list);
print_r($new_list);
Maps the contents of the first argument as keys and the contents of the second argument as values, in their defined order.
I haven't tested it, but this should work
foreach ($array as $key => $value) {
$array[$value] = $value;
unset($array[$key]);
}
That should do it
That is redundancy at its finest. It makes little sense to have keys matching their values, and probably highlights the need for a design change, or a potential optimisation somewhere in your application. Turning this:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
into this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
effectively reduces the amount of information you are storing, since you the developer know in advance that keys should match values.

Categories