split a string of filenames from a database - php

I have a MySQL table called products with a column (images)
there are many filenames in this column seperated by [] and ,
like:
[image-1.jpg],[image-2.jpg],[image-4.jpg],[image-5.jpg]
and so on...
i want to be able to extract the images filenames so they look like:
image-1.jpg
image-2.jpg
image-3.jpg
image-4.jpg
image-5.jpg
here is my current PHP:
<?php
$images = explode(',',$project['images']);
foreach($images as $image)
{
$display_image = substr($image, 1, -1);
?>
<tr>
<td><img src="/img/project-gallery/<?php echo $display_image; ?>" width="160px" /><br />
<input type="checkbox" name="current_images<?php echo $project["sequence"]; ?>" id="current_images<?php echo $project["sequence"]; ?>" value="image_id_checkbox_<?php echo $project["sequence"]; ?>" /></td>
</tr>
<?php
}
?>
so i have a checkbox under each image, which i want to be able to deleted the selected [filename.extn], from the images column in the database.
for example, if i check image-1.jpg checkbox i would want the images column to end up like:
image-2.jpg
image-3.jpg
image-4.jpg
image-5.jpg

preg_split — Split string by a regular expression
This will do it...
$images = preg_split("/[\[\],]+/", $project['images']);

Try this:
<?php
$string = '[image-1.jpg],[image-2.jpg],[image-3.jpg],[image-4.jpg],[image-5.jpg]';
$str_arr = explode(',', $string);
foreach($str_arr as $key => $value)
{
$value = trim($value, '[]');
echo $value."<br />";
}
?>
--
Thanks ....

Related

php variable from random list

I am trying to include a piece of text from a config file into a php file that generates a random number of tags from a seperate list of tags.
Code to generate the tags :
<?php
include '../config/filenames.php';
$keywords = explode(",", file_get_contents("taglist.php"));
shuffle($keywords);
$keys = array();
foreach (array_slice($keywords, 0, 20) as $word) {
$word = trim($word);
$keys[] = $word;
}
echo join(',', $keys);
?>
This is the taglist :
<a href='<?php echo $filename_a?>'>test</a>,
<a href='<?php echo $filename_a?>'>test2</a>,
<a href='<?php echo $filename_a?>'>test3</a>,
<a href='<?php echo $filename_a?>'>test4</a>
For some reason it is not including the $filename_a. It looks like the result of the random data is not parsing the php, but simply printing the piece of php code rather then the result of it.
Can someone help ?

separate meta keys on implode

<?php echo strip_tags(stripslashes($row = implode(['meta_keys']))) ?>
all it shows is "meta_keys" as display, and not the info from the database.
I'm trying to get each key individually linked on an <a href=""> tag.
I know I need to array, but any ideas?
$meta_keys = explode(',', $row['meta_keys']);
foreach ($meta_keys as $key) {
echo strip_tags($key) . ' ';
}

search for partial or complete text in array

I have an HTML search form:
<form method="post">
<input type="text" name="term" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
I then have a foreach loop to check if the array item contains the search term:
<?php if (is_array($data['page'])): ?>
<?php foreach ($data['page'] as $item): ?>
<?php foreach($item as $item_member): ?>
<?php if(strpos($item_member, $_POST['term']) !== FALSE): ?>
<tr>
<?php foreach ($columns as $key => $column): ?>
<?php $key = parse_class($key); ?>
<td class="<?php echo $key['class']; ?>"><a class="cell-link"
href="<?php echo $details_link . $item[$details_id_field]; ?>">
<?php echo (!empty($item[$key['column']])) ? $item[$key['column']] : ' '; ?>
</a></td>
<?php endforeach; ?>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
Here is a more readable version
if(is_array($data['page'])){
foreach($data['page'] as $item){
if(array_search($_POST['term'], $item)){
echo "<tr>";
foreach($columns as $key => $column){
$key = parse_class($key);
echo '<td class="' . $key['class'] . '"><a class="cell-link" href="' . $details_link . $item[$details_id_field] . '">';
echo (!empty($item[$key['column']])) ? $item[$key['column']] : ' ';
echo '</a></td>';
}
echo '</tr>';
}
}
}
At the moment, the search only works if the search term is exactly the same as the name in the item.
The array item contains the following information:
234|test|21|Jul 28, 2013|0%|1375026328|1375026328|Test)/
I'm really only interested in matching the second value in item (in the example above "test" with the search term "term"
I have tried in_array, strpos with no luck.
For the example above, at the moment a result is only brought up if I enter the exact text "test" in the search form. If I enter "tes" for example which is an incomplete search phrase, nothing shows.
If I understand correctly $item holds the array you referred to.
Add another foreach to iterate the elements of $item and for every one of the items preform a strpos($item_member, $_POST['term']) check instead of array_search:
<?php foreach($item as $item_member)): ?>
<?php if(strpos($item_member, $_POST['term']) !== FALSE): ?>
<?php // here do what you gotta do ?>
<?php endif; ?>
<?php endforeach; ?>
BUT, if you already know that you're looking to match only the second element - you can skip this foreach and simply do:
<?php if(strpos($item[1], $_POST['term']) !== FALSE): ?>
This check will return true (or actually the beginning index of the match that was found) for any valid sub-string of test - so if you want only sub-string that start at index 0 you can change the test instead of: !== FALSE
to
=== 0
By the way - the : syntax is hard to read - I would change it.
First of all, I don't know what you intend 234|test|21|Jul 28, 2013|0%|1375026328|1375026328|Test)/ to mean. Is that a string at the 0 index of the array? Are the pipes just a way to visually separate the array elements?
Also, your code is also very hard to read, so I didn't read it. That said, I think I understand what you're trying to do. Let's say you have an array with some stuff in it:
$arr = array(
234,
'test',
'Jul 28, 2013',
'testers',
);
And let's say you have a user input string:
$input = 'tes';
We want to determine if any of the elements in the array contain this string:
$matches = array();
foreach($arr as $element) {
if (strpos("$element", $input) !== false) {
#match found, store it
$matches[] = $element;
}
}
var_dump($matches); //contains two elements, 'test', and 'testers'
Output of that var_dump:
array(2) {
[0]=>
string(4) "test"
[1]=>
string(7) "testers"
}
You should be able to adapt this to your specific use case. By the way, the quotes around $element in that strpos call are to cast it to a string. I doubt this is necessary in PHP (can't recall), but just in case ...

while loop inside a while loop? Separating data from PHP

while($row = mysql_fetch_array($result))
//Template for each card in search result
{
echo '<div class="sleeve">';
echo '<div class="card ', $row['name'], '">';
echo '<div class="front face">';
echo '<img src="/', $row['cardset'], '/', $row['name'], $row['altart'], '.jpg"', ' alt="', $row['name'], '" />';
echo '</div>';
echo '<div class="back face">';
echo '<a id="name">', $row['name'], '</a><br/>';
echo '<form name="info" action="">';
echo '<select name="set">';
//while???
echo '<option value="Zendikar">', $row['sets'],'</option>';
echo '</select>';
echo 'Foil:<input type="checkbox" name="foil" value="true"/><br/>';
echo '<select name="condition">';
echo '<option value="Near Mint">Mint</option>';
echo '<option value="Played">Played</option>';
echo '<option value="Damaged">Damaged</option>';
echo '</select>';
echo 'Trade:<input type="checkbox" name="trade" value="true"/ <br/>';
echo '</form>';
echo '<b>Rulings:</b> <br/>';
echo $row['rulings'];
echo '</div>';
echo '</div>';
echo '</div>';
}
//while??? It might be hard to see in that mess of echoes, but there's a section that I have no idea how to deal with. PHP is grabbing rows of info, and populating them nicely. It fills the screen with little boxes of info.
In this section, that I don't know how to deal with, the data in one of the rows contains multiple things (thing1, thing2, thing3) separated by a (, ) each time. I need each of those things in a new thing1
So I feel like there would be another while loop inside each card?
You're on the right track with a loop. Try something like this, which explodes the string into an array, based on the comma delimiter, with explode():
echo '<select name="set">';
foreach( explode( ',', $row['sets']) as $item)
echo '<option>', $item, '</option>';
echo '</select>';
You probably need a foreach statement there after exploding the String into an array:
instead of the //while line and the following one:
foreach (explode(',', $row['sets']) as $value)
echo '<option value="', $value, '">', $value,'</option>';
I guess you may actually have another value for each row (one to be displayed, the other one is the actual value you want to set), but then the String would look much more like "(key1=value1, key2=value2)" and then you need a little more work, but you get the idea.
Hope this helps.
Yes, you would need to first explode that row into an array
$list_of_things = explode(",", $row['whatever']);
and then use a while, or a foreach:
$thing_options = '';
foreach($list_of_things as $thing)
$thing_options .= "<option>$thing</option>";
You might also find the here document syntax useful:
print <<<TEMPLATE
<div class="sleeve">
<div class="card {$row['name']}">
<div class="front face">
<img src="/{$row['cardset']}/{$row['name']}{$row['altart']}.jpg"
alt="{$row['name']}" />
</div>
<div class="back face">
<a id="name">{$row['name']}</a>
<br/>
<form name="info" action="">
<select name="set">
{$thing_options}
<option value="Zendikar">{$row['sets']}</option>
</select>
...
TEMPLATE;
While all of the answers telling you to explode() the array are correct, I can't help but think that having a db column filled with comma separated values are a symptom that your database is not normalized. You should check out the following link for an introduction to db normalization: http://mikehillyer.com/articles/an-introduction-to-database-normalization/
I'd also recommend not echoing out HTML. Ideally, your PHP scripts should follow this pattern:
All PHP processing up front, including database queries and form handling. Results should be stored in variables.
|
|
|
V
Almost pure HTML template/view, with just enough display logic (if/else, loops, echo) to actually display the results you stored in the variables from step 1.
You'll find that debugging/editing is a lot simpler if you let PHP be the brains and HTML be the beauty. Just like how markup and styles should be separate, the same goes for scripting and display.
You can use PHP's explode-method to split the comma separated string into its values, and then handle that array in a foreach loop:
$raw = "one,two,three";
$values = explode("," $raw);
foreach($values as $value) {
echo $value;
}

array search is not working in php

I am trying to find picid in array but it's not working. When I echo it, nothing appears.
Here is my code
<?php $psql=mysql_query("select * from gallery where userId='$miid'");
$photo1 = array();
while($photo=mysql_fetch_assoc($psql)) {
$photo1[]=$photo;
print_r($photo);
}
foreach($photo1 as $k => $v){
if($v['picId']==$mipic){
$pic="uploads/".$v['photo'];
echo ">>>". $key=array_search($v['picId'],$photo1);
?>
NEXT
<img src="<?php echo $pic; ?>" width="300px" height="300px">
PREVIOUS
<?php
}
}?>
array_search is not recursive. $v exists in $photo1, while $v['picId'] only exists in $v.
That makes $key=array_search($v['picId'],$photo1) return false which, when you echo it, will print as nothing.
I am not sure why you are using array_search at all. In order to retrieve the next and previous picId, try this:
NEXT
<img src="<?php echo $pic; ?>" width="300px" height="300px">
PREVIOUS
Beware though that one of the hrefs is modules/gallery/miloader.php while the other is just miloader.php. So unless you actually have two different miloader.php files (one in each of the directories), one of them is wrong.

Categories