$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]
Related
Here what I got in view
I want to show it as Separate divs based on vendor name
How can i Group the vandor names and Show in different divs ?
I don't know how the data is being stored/retrieved but here is how I might do such sorting - assuming the variable $rows is set contains an associative array of all rows (similar to the results of a basic database query) and assuming "vendor" is the column name for the vendors (TSZ, TSR, etc), "sku" is the name of the SKU column, and "store_price" is the name of the store price column:
<?php
$vendorData = [];
foreach( $rows as $row ) {
if( !isset($vendorData[$row['vendor']]) ) {
$vendorData[$row['vendor']] = '';
}
$vendorData[$row['vendor']] .= '<div class="sku">' .
$row['sku'] . '</div>' .
'<div class="price">' . $row['store_price'] . '</div>';
}
foreach( $vendorData as $vendorName => $vendorHTML ) {
echo '<div id="' . $vendorName . '" class="vendor">' .
'<h3 class="name">' . $vendorName . '</h3>' .
'<div class="data">' . $vendorHTML . '</div></div>';
}
?>
Here is thing what you need:-
$newDataRow = []
foreach($dataRows as $dataItemRow):
$newDataRow[$dataRows['vendor']][] = $dataItemRow;
endforeach;
$op = '';
foreach($newDataRow as $vandorName => $vandorItemData):
$op .= '<div class="vendor_item_group">';
$op .= '<div class="vendor_name">'.$vandorName.'</div>';
$op .= '<div class="item_group">';
foreach($vandorItemData as $record):
$op .= '<span>'.$record['sku'].'</span>';
$op .= '<span>'.$record['price'].'</span>';
endforeach;
$op .='</div>';
$op .= '</div>';
endforeach;
echo $op;
Output Should be like this:-
TSZ TSR
TSZ K377 TSR319
2300 2250
TSR319
2300
I got an error saying
Object of class DOMNodeList could not be converted to string on line
This is the line which contains the error:
$output .= '<li><a target="_blank" href="' . $postURL . '">' .
$title->nodeValue . '</a></li>';
DOM
My code:
$postTitle = $xpath->query("//tr/td[#class='row1'][3]//span[1]/text()");
$postURL = $xpath->query("//tr/td[#class='row1'][3]//a/#href");
$output = '<ul>';
foreach ($postTitle as $title) {
$output .= '<li><a target="_blank" href="' . $postURL . '">' . $title->nodeValue . '</a></li>';
}
$output .= '</ul>';
echo $output;
How can I resolve the error?
You're fetching two independent node list from the DOM, iterate the first and try to use the second one inside the loop as a string. A DOMNodeList can not be cast to string (in PHP) so you get an error. Node lists can be cast to string in Xpath however.
You need to iterate the location path that is the same for booth list (//tr/td[#class='row1'][3]) and get the $title and $url inside the loop for each of the td elements.
$posts = $xpath->evaluate("//tr/td[#class='row1'][3]");
$output = '<ul>';
foreach ($posts as $post) {
$title = $xpath->evaluate("string(.//span[1])", $post);
$url = $xpath->evaluate("string(.//a/#href)", $post);
$output .= sprintf(
'<li><a target="_blank" href="%s">%s</a></li>',
htmlspecialchars($url),
htmlspecialchars($title)
);
}
$output .= '</ul>';
echo $output;
I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.
This is tailing off my other question which was successfully answered: stackoverflow.com/questions/8597929/need-to-create-li-with-list-of-different-links-using-php-explode-method
so now I have this:
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and that, using the following in a textarea which is defined to "my_custom_output":
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
and the result is
text1
text2
text3
which are successfully linked and styled. (i didnt make them links because stackoverflow doesn't let me post more than two links because i only have 3 rep).
So my next and final desired task is to do this:
text1
description 1
text2
description 2
text3
description 3
where the text1 etc are linked like before but the descriptions are not linked.
So I will do my best, right here in stackoverflow, to try it. However, I expect I will need some help. Let's go:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and to use the following in the textarea which is is defined to "my_custom_output":
text1:text1-page-url;Text1 Description
text2:new-text2-page;Description For Text2
text3:different-page-text3;A Text3 Description
and I need the output to be:
text1
Text1 Description
text2
Description For Text2
..etc
I don't know if semicolon will work, but I can't use a space (\s) because there are spaces in the description. I am open to suggestions.
====================================================
MY NEWEST TRY:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode($separator3,$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
IT WORKS!!! =D
Not sure if I understand this well enough (I'm not sure what get_custom_field() gets you - can't find that as a regular PHP function), but when you explode an item that has multiple instances of the delimiter, you'll get multiple arrays.
So:
$textarea = "text1:text1-page-url;Text1 Description";
$data = explode(':',$textarea);
// at this point $data[0] will contain "text1", while $data[1] contains text1-page-url;Text1 Description"
$descarray = explode(';',$data[1]);
// then $descarray[0] contains "text1-page-url" and $descarray[1] contains "Text1 Description" so you can echo this out however you like.
To work with your code..
Assume each $item is each row at this point, like this:
$item = "text1:text1-page-url;Text1 Description";
Then this will do the trick:
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode(';',$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
I'd slightly optimize the algorithm as there is no need for second explode(). Just separate substrings within one row with the same separators (and don't forget to escape that separator inside all your data):
<?php
$row_separator = "\n";
$line_separator = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($row_separator, $textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links, $item_desc) = explode($line_separator, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And here is the data format I suggest to use (separate all fields by :)
text1:text1-page-url:Text1 Description
text2:new-text2-page:Description For Text2
text3:different-page-text3:A Text3 Description
I want to be able to parse the following json data. It was constructed from a php array using jsonencode. I've added the json below to help you understand it. I'd like to be able to display the json in a bulleted form. It show two records with associated category array and tags array. Im open to using any libraries to help.
{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}
I want to be able to parse it and display like this.
Liverpool Football Club
Content goes
here
Categories
Football Club
Tags
England
EPL
UPDATE: Sorry i need to parse it in javascript.
Try this:
$json = '{"0":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"908","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Liverpool Football Club","post_content":"Content goes here...","post_name":"liverpoolfc","guid":"http://www.liverpoolfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0},"1":{"categories":[{"name":"Football Club","slug":"football-club"}],"tags":[{"name":"England","slug":"england"},{"name":"EPL","slug":"epl"},{"name":"Europe","slug":"europe"},{"name":"Champions","slug":"champions"}],"ID":"907","post_author":"78350","post_date":"2010-10-18 10:49:16","post_title":"Everton Football Club","post_content":"Content goes here","post_name":"evertonfc","guid":"http://www.evertonfc.tv","post_type":"post","comment_count":"0","comment_status":"open","relevance_count":0}}';
$array = json_decode($json, true);
foreach ($array as $item) {
echo '<ul>' . PHP_EOL;
echo '<li>' . $item['post_title'] . '</li>' . PHP_EOL;
echo '<li>' . $item['post_content'] . '</li>' . PHP_EOL;
/* Display Categories */
echo '<li>Categories' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['categories'])) {
foreach ($item['categories'] as $category) {
echo '<li>' . $category['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Categories Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
/* Display Tags */
echo '<li>Tags' . PHP_EOL;
echo '<ul>' . PHP_EOL;
if (!empty($item['tags'])) {
foreach ($item['tags'] as $tag) {
echo '<li>' . $tag['name'] . '</li>' . PHP_EOL;
}
} else {
echo '<li>No Tags Available</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
}
UPDATE Are you asking on how to do this in PHP or in Javascript/jQuery? You didn't quite explain what you were doing with it.
UPDATE Here it is using Javascript/jQuery: http://jsfiddle.net/wgjjR/
//<div id="container"></div>
//var json = {}; // this is your JSON object
var container = $('#container'), html = [];
for (var key in json) {
var item = json[key];
html.push('<ul>');
html.push('<li>' + item.post_title + '</li>');
html.push('<li>' + item.post_content + '</li>');
html.push('<li>Categories<ul>');
for (var cat in item.categories) {
cat = item.categories[cat];
html.push('<li>' + cat.name + '</li>');
}
html.push('</ul></li>');
html.push('<li>Tags<ul>');
for (var tag in item.tags) {
tag = item.tags[tag];
html.push('<li>' + tag.name + '</li>');
}
html.push('</ul></li>');
html.push('</ul>');
}
$json = json_decode($inputJson, true);
foreach($json as $key => $value)
{
// do somethig
}
Use json_decode
$json = json_decode($some_json, true);
$element1 = $json["item"]["element1"];
$element2 = $json["item"]["element2"];
Repeat to extract all the values you require.