Let's say I am getting requests such as:
http://www.example.com/index.php?id=123&version=3&id=234&version=4
Is it possible to extract these in a simple way inside my php code? I realize I could get the entire querystring with javascript using window.location.href and handle it manually but I'm looking for something more elegant. The requests can contain any number of version/id pairs but I can assume that the query is well-formed and have no obligation to handle invalid strings.
If you can change the field name to include [], then PHP will create an array containing all of the matching values:
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
If you don't have the ability to change the field names, then as you say, you'll have to parse the querystring yourself.
According to this comment from the PHP manual, PHP's query string parser will drop duplicate params... so I don't think that PHP is a good fit for what you want to do (except in that it has the same capacity as javascript to get the raw query string, with which you can do whatever you want)
Assuming you have some control over the request, suffix the name with [] and PHP will generate arrays instead of dropping all but one.
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
Since they are pairs you'll probably want to fix the order they appear in using indexes.
http://www.example.com/index.php?id[0]=123&version[0]=3&id[1]=234&version[1]=4
Just extract the keys and values of $_GET, use the function as:
print_array('$_GET...',$_GET);
... and the function code will be:
function print_array($title, $arr) {
echo '<table width="100%" style="padding:10;">';
echo '<tr><td width="30%" style="text-align:right; background-color:bisque;">key of </td><td style="background-color:bisque;">'.$title.'</td></tr>';
foreach($arr as $key => $value) {
echo '<tr>';
echo '<td style="text-align:right; color:grey;">';
echo $key;
echo '</td>';
echo '<td>';
echo $value;
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
Not as rounded or reliable as methods mentioned above but I use this to remove the need to [] in urls without worrying about rewriting.
$aQuery = explode("&", $_SERVER['QUERY_STRING']);
$aQueryOutput = array();
foreach ($aQuery as $param) {
if(!empty($param)){
$aTemp = explode('=', $param, 2);
if(isset($aTemp[1]) && $aTemp[1] !== ""){
list($name, $value) = explode('=', $param, 2);
$aQueryOutput[ strtolower(urldecode($name)) ][] = urldecode(preg_replace('/[^a-z 0-9\'+-]/i', "", $value));
}
}
}
Related
This is a fun one.
I have a function that produces an array from mySQL...or better yet, it produces an array of arrays. Follow?
I've figured out how to drill down in to the array to display them into a working table. As so:
<table id="list_table" cellpadding="1" cellspacing="1">
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $key => $value)
{
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
?>
</table>
HOWEVER, I only want to call specific <td>'s, which means, I have to call references to the specific column indexes. I've tried $value['1'], but it just does some crazy stuff. so, where I'm stuck is I do not know where to call the specific column indexes that I want.
You're nesting/overwriting your $key and $value variables. That is likely completely messing things up.
Try:
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $k => $v)
{
echo '<td>' . $v . '</td>';
}
echo '</tr>';
}
?>
That might help you solve your issues.
You stated " I have to call references to the specific column indexes" and "I just need to know how to specify which columns to use. (or which indexes/keys to display)".
I suspect your issue is actually more involved than this, but the answer to that question is to use the standard syntax for multidimensional arrays. E.g., $array['index1']['index2'].
More information about the PHP array syntax is here. Please clarify your question if you need more information.
I think there is a problem when I echo $whereArray and orderByArray. If I type in a word such as "Question" and then submit it, I expect it to display in the echos "%".Question."%"; for both arrays. But instead in both echos it just displays "Array" for both echos. Does this mean that both arrays are not working when it comes to storing in the values?
$searchquestion = $_GET['questioncontent'];
$terms = explode(" ", $searchquestion);
$whereArray = array();
$orderByArray = array();
//loop through each term
foreach ($terms as $each) {
$i++;
$whereArray[] = "%".$each."%";
$orderByArray[] = "%".$each."%";
}
echo $whereArray;
echo $orderByArray;
echo() only works for strings. PHP converts your array to "Array" as a fallback.
When you're debugging, you should use var_dump(). It will tell you the type of the object and its content.
Use var_dump or print_r instead of echo (they are functions, not constructs like echo is).
An array needs to be printed out using a special function such as print_r. If you want to print out a value in your array try:
echo $whereArray[0];
To get the first element. Be careful because if the array is empty you will get an error.
you can also loop through them
foreach($arrayname as $value)
echo $value;
or
echo implode("",$arrayname);
i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag <ul><li>...?
i have in database this: a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}
LIKE:
Coffee
Game Notes
Internet
Pool
You need to use unserialize(), as you said, with a foreach() loop, like this:
$arr = unserialize($dbString);
echo "<ul>";
foreach($arr as $key => $val)
{
echo "<li>$val</li>";
}
echo "</ul>";
This will echo a list containing value because foreach() iterates through the unserialize()d array, as you have specified in your question.
The $key => $part is the icing on the cake for foreach(); if you want the get the array key, simply reference $key. If you want the data for that key, use $val.
If you want to echo just one element (your example is Internet), just don't use a loop and reference it by key (integer):
$arr = unserialize($dbString);
echo $arr[2];
This echos the third element in the array on it's own.
Original question
Unserialize the data and loop over it printing it out. Notice that I have also added in checks to see that we are getting back an array and that it contains something before looping over it.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Internet
I think this is what you are asking for. To only echo out the value if its Internet.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
if('Internet' != $value) {
continue;
}
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
JSON
If you can I would stop using serialize and use json_encode instead. It is easier to encode and decode in more programming languages and it is easier to edit by humans should you need to update the DB directly.
i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.
I have an html table that is populated from a text file, formatted and semi colon separated.
I would like the user to have the option of sorting alphabetically with either of the columns when clicking on the column name (header).
How do I do this in php?? Or is there another way of doing this? Thanks for your help.
Sample raw data/input looks like this:
TYPE=abc;PART=georgetown;FILE=goog_abc.dat.2010122211.gz
TYPE=xyz;PART=ucny;FILE=aol_xyz.dat.2010122209.gz
Php code for table:
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('/temp/tab.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach ($rows as $row) {
echo '<tr>';
foreach($columns as $column){
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
I'd recommend using some jQuery. In fact, this looks like exactly what you need.
Edit Put this in between your <head> tags
<script type="text/javascript">
$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
}
);
</script>
Or you can put it in a separate file and link it like this. (Probably only do this if you intend to write more javascript.
<script type="text/javascript" src="path/to/file.js"></script>
Use something javascript based to sort the table after you draw it. Trying to add this kind of sorting from within PHP is painful and not needed unless you have multiple pages of data (then you need PHP to sort it in the database side). Here is a list that gives you a LOT of options for sortable tables - you should be able to apply many of those to your table after you generate it using PHP.
http://www.webdesignbooth.com/15-great-jquery-plugins-for-better-table-manipulation/