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 ...
Related
I have the following piece of HTML in a PHP app with an array including Group and Items. First I want to sort them by Groups, then within Groups have Items separated by comma (Item1, Item2, Item3), without ending comma.
<dl>
<?php $groupname = '' ?>
<?php foreach ($product['product_filters'] as $product_filter) { ?>
<?php if ($groupname != $product_filter['group']) { ?>
<?php $groupname = $product_filter['group']; ?>
<?php echo '<dd>' . $product_filter['group'] . '</dd>'; ?>
<?php } ?>
<dt>
<?php echo $product_filter['name']; ?>
</dt>
<?php } ?>
</dl>
I want to have a the following result, but I don't know how to manage it and which loop should I use:
Group 1
G1_Item_1, G1_Item_2
Group 2
G2_Item_1, G2_Item_2, G2_Item_3
You could use two loops: one to restructure your data into groups, and one just for outputting it in the desired format. Note that you used <dt> and <dd> in the opposite sense: the groups are the titles, so use <dt> for them.
Also, your code becomes much more readable if you don't open and close the php tag on every line. Try to make code blocks that don't have such interruption: it will make it so more readable.
Here is the suggested code:
<?php
// Create a new structure ($groups): one entry per group, keyed by group name
// with as value the array of names:
foreach ($product['product_filters'] as $product_filter) {
$groups[$product_filter['group']][] = $product_filter['name'];
}
// Sort it by group name (the key)
ksort($groups);
// Print the new structure, using implode to comma-separate the names
foreach ($groups as $group => $names) {
echo "<dt>$group</dt><dd>" . implode(', ', $names) . "</dd>";
}
?>
See it run on eval.in.
<?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) . ' ';
}
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 ....
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;
}
I'm trying to make Drupal print a list with two different fields in the same array. So first comes field A, then field B and it prints in this way until the whole array is printed.
The result I'm trying to get is something like
<tr>
<td>Field_1[value1]</td>
<td>Field_2[value1]</td>
</tr><tr>
<td>Field_1[**value'n'**]</td>
<td>Field_2[**value'n'**]</td>
</tr>
Until all values are printed.
EDIT.
Figured out one way of achieving this directly in node--testnode.tpl.php.
<table>
<?php if ($content['field_test'][1]): ?>
<tr><td><?php print render($content['field_test'][0])?></td><td><?php print render($content['field_test'][1])?></td></tr>
<?php endif; ?>
<?php if ($content['field_test'][3]): ?>
<tr><td><?php print render($content['field_test'][2])?></td><td><?php print render($content['field_test'][3])?></td></tr>
<?php endif; ?>
<?php if ($content['field_test'][5]): ?>
<tr><td><?php print render($content['field_test'][4])?></td><td><?php print render($content['field_test'][5])?></td></tr>
<?php endif; ?>
</table>
Second fix, only manual work is to say how many repetitions you want.
<dl class="My Class">
<?php
$i = 0;
$counter = 2 * render ($content['field_counter_slides'][0]) -1;
while ($i <= $counter):
if ($content['field_test'][1]){
echo "<dt>";
print render ($content['field_test'][$i]);
$i++;
echo "</dt><dd>";
print render ($content['field_test'][$i]);
echo "</dd>";
$i++;
}
endwhile;
?>
</dl>
It's quite hard to answer without knowing more but something like this would probably do it:
$header = array();
$rows = array();
foreach ($node->field_my_field[$langcode] as $key => $field_entry) {
$rows[] = array(
$field_entry['value'],
$node->field_my_second_field[$langcode][$key]['value']
);
}
$output = theme('table', array('header' => $header, 'rows' => $rows));
You'd have to make sure yourself that there are equal numbers of entries for each field so that there will always be a field_my_second_field entry for each run through the foreach loop.