I have a block of PHP code where I'm using two counters (one specifically for a particular key of featured if the value is 1.
So far, the counter works by putting any records where featured == 1 in $cnt1 and everything else in $cnt2. However, this doesn't do anything for my sorting.
How can I make this so that the final array puts all featured ($cnt1) records at the top of the array/the first results?
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$lat = get_post_meta($id,'_awpcp_extra_field[36]',true);
$lon = get_post_meta($id,'_awpcp_extra_field[37]',true);
$area = get_post_meta($id,'_awpcp_extra_field[38]',true);
$amnt = get_post_meta($id,'_awpcp_price',true)/100;
$ttle = get_the_title($id);
$link = get_permalink($id);
$desc = get_the_excerpt($id);
$date = get_the_time('m/d/Y',$id);
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$counter_name = ($is_featured == 1) ? 'cnt1' : 'cnt2';
$ress[$$counter_name]['featured'] = $is_featured;
$ress[$$counter_name]['lat'] = $lat;
$ress[$$counter_name]['lon'] = $lon;
$ress[$$counter_name]['area'] = $area;
$ress[$$counter_name]['amnt'] = $amnt;
$ress[$$counter_name]['ttle'] = $ttle;
$ress[$$counter_name]['link'] = $link;
$ress[$$counter_name]['desc'] = $desc;
$ress[$$counter_name]['date'] = $date;
$ress[$$counter_name]['count'] = $counter_name;
if($imgpath){
$ress[$$counter_name]['imgs'] = $imgpath;
}else{
$ress[$$counter_name]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$$counter_name++;
}
}
Related
In my wordpress functions file, I'm getting sql query results of only post IDs, then taking those IDs to create an array that I send to my page.
This works perfectly but I want to re-order it based on one of the values I generate in the array process. I have a value of 'featured' and I want to make it so that any results where featured = 1 are first in the array.
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$ress[$cnt]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$cnt]['imgs'] = $imgpath;
}else{
$ress[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
echo json_encode($ress);
}
Is there a way to simply use conditions in order to put those values first in the array?
Using a function get_post_meta in an array is bad practice. I would advise first querying the database to extract data from custom fields.
However, I think there are two ways to answer your question:
Use 2 arrays and merge them together after iteration:
$myresults = $wpdb->get_results( $sqlStatement );
$ress1 = $ress2 = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$array_name = !empty($is_featured) ? 'ress1' : 'ress2';
$$array_name[$cnt]['featured'] = $is_featured;
if($imgpath){
$$array_name[$cnt]['imgs'] = $imgpath;
}else{
$$array_name[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
$ress = array_merge($ress1, $ress2);
echo json_encode($ress);
}
Use 2 counters:
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt1 = 0;
$cnt2 = 1000000;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$counter_name = !empty($is_featured) ? 'cnt1' : 'cnt2';
$ress[$$counter_name]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$$counter_name]['imgs'] = $imgpath;
}else{
$ress[$$counter_name]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$$counter_name++;
}
}
$ress = array_values( $ress );
echo json_encode($ress);
}
I'm very new to learning how to use XML, I know a few programming languages. I've tried searching for this answer but I get very confused and cannot relate back to how I would implement this in my code. At the moment I would like to be able to sort prices
Here's an example of how it currently looks
<?php
$xmlFile = "hotel.xml";
$HTML = "";
$count = 0;
$dom = DOMDocument::load($xmlFile);
$hotel = $dom->getElementsByTagName("hotel");
foreach($hotel as $node)
{
$city = $node->getElementsByTagName("City");
$city = $city->item(0)->nodeValue;
$type = $node->getElementsByTagName("Type");
$type = $type->item(0)->nodeValue;
$name = $node->getElementsByTagName("Name");
$name = $name->item(0)->nodeValue;
$price = $node->getElementsByTagName("Price");
$price = $price->item(0)->nodeValue;
if (($type == $_GET["type"]) && ($city == $_GET["city"]) )
{
$HTML = $HTML."<br><span>Hotel: ".$name."</span><br><span>Price: ".$price."</span><br>";
$count++;
}
}
if ($count ==0)
{
$HTML ="<br><span>No hotels available</span>";
}
echo $HTML;
?>
I want to create an RSS feed in PHP based on other RSS feeds. That works.
But, Now I want to change how many items are shown in the new created feed. This based on calculation of the items of another feed.
I use this script for the calculation, which works fine:
<?php
$url = 'http://www.nu.nl/rss/Algemeen';
$xml = simplexml_load_file($url);
$tags = array();
foreach($xml->channel->item as $item) {
$children = $item->children(); // get all children of each item tag
foreach ($children as $node) {
$tags[] = $node->getName(); // get the node name of each children
}
}
$test = count($tags);
$count = array_count_values($tags); // count the values
?>
<?php
$mystring = count($tags);
$findme = '3';
$pos = strpos($mystyring, $findme);
?>
<?php
$artikel = ($mystring / 5);
echo $artikel;
?>
I use this script, magpierss, fow creating a new feed:
<?php
/**
* Setup
*
*/
$DOMAIN_NAME = 'http://sitename.nl/';
$FEED_URL = $DOMAIN_NAME . 'rss/full.php';
$SITE_TITLE = 'test';
$SITE_DESRIPTION = '-';
$SITE_AUTHOR = 'test2';
$RSS_CACHE = "/tmp/rsscache";
$RSS_CACHE_EXP = 3600;
$FEED_LIST = array(
'http://www.nu.nl/rss/Economie',
'http://www.nu.nl/rss/Internet'
);
/**
* Do not modify below this point
*
*/
define('MAGPIE_CACHE_DIR', $RSS_CACHE);
define('MAGPIE_CACHE_AGE', $RSS_CACHE_EXP);
define('MAGPIE_OUTPUT_ENCODING', 'utf-8');
// include required files
require_once ('magpierss-0.72/rss_fetch.inc');
include ('feedcreator.class.php');
/* Set RSS properties */
$rss = new UniversalFeedCreator();
$rss->useCached();
$rss->title = $SITE_TITLE;
$rss->description = $SITE_DESRIPTION;
$rss->link = $DOMAIN_NAME;
$rss->syndicationURL = $FEED_URL;
$rss->encoding = 'utf8';
/* Set Image properties
$image = new FeedImage();
$image->title = $SITE_TITLE . " Logo";
$image->url = $SITE_LOG_URL;
$image->link = $DOMAIN_NAME;
$image->description = "Feed provided by " . $SITE_TITLE . ". Click to visit.";
$rss->image = $image;
*/
function showSummary($url, $num = 10, $showfullfeed = false) {
global $rss, $DOMAIN_NAME, $SITE_AUTHOR, $SITE_TITLE;
$num_items = $num;
# $rss1 = fetch_rss($url);
if ($rss1) {
$items = array_slice($rss1->items, 0, $num_items);
foreach ($items as $item) {
$href = $item['link'];
$title = $item['title'];
if (!$showfullfeed) {
$desc = $item['description'];
} else {
$desc = $item['content']['encoded'];
}
// $desc .= '
//Copyright © '.$SITE_TITLE.'. All Rights Reserved.
//';
$pdate = $item['pubdate'];
$rss_item = new FeedItem();
$rss_item->title = $item['title'];
$rss_item->link = $item['link'];
$rss_item->description = $item['content']['encoded'];
$rss_item->date = $item['pubdate'];
$rss_item->source = $DOMAIN_NAME;
$rss_item->author = $SITE_AUTHOR;
$rss->addItem($rss_item);
}
} else {
echo "Error: Cannot fetch feed url - " . $url;
}
}
// Fetch all feeds
foreach($FEED_LIST as $v) showSummary($v);
// Sort items by date
function __usort($ad, $bd) {return strtotime($bd->date) - strtotime($ad->date);}
usort($rss->items, '__usort');
// Display items
$rss->saveFeed("RSS1.0", $RSS_CACHE . "/feed.xml");
How could I let the variable $artikel decide how many items are showed in the feed?
I have the following code that queries multiple tables to get information about activities. I would like to convert the query result into array and call it whenever needed.
My question is: can this query be converted into array?
<?php
function view_full_activity($activity_field){
global $connection;
$contact_id = $_REQUEST['contact_id'];
$activity_id = $_REQUEST['activity_id'];
$get = "SELECT * FROM activity_base WHERE activity_id = '$activity_id' "
or die("Error: ".mysqli_error($connection));
$query = mysqli_query($connection, $get);
//Get activity base information
while ($activity = mysqli_fetch_array($query)){
$activity_related_to_id = $activity ['activity_related_to_id'];
$activity_id = $activity['activity_id'];
$activity_type_id = $activity['activity_type_id'];
$activity_entity_type_id = $activity['activity_entity_type_id'];
$activity_title = $activity['activity_title'];
$activity_due_date = $activity['activity_due_date'];
$activity_created_by = $activity['activity_created_by'];
$activity_created_on = $activity['activity_created_on'];
$activity_status_code_id = $activity['activity_status_code_id'];
$activity_type_icon;
$activity_due_date = $activity['activity_due_date'];
$activity_create_date = date("m-d-Y", strtotime($activity['activity_created_on']));
//Reverse Date
$activity_due_date = date("m-d-Y ", strtotime($activity_due_date));
if ($activity_type_id == "1"){
$activity_type_icon = "fa fa-envelope";
}else if ($activity_type_id == "3"){
$activity_type_icon = "fa fa-suitcase";
}else if ($activity_type_id == "2"){
$activity_type_icon = "fa fa-phone";
}
if ($activity_entity_type_id == "1") {
$acitvity_url = "acct_id";
$acitivty_is_for ="accounts_base";
$page_url = "account-profile.php";
}else if ($activity_entity_type_id == "2") {
$acitvity_url = "contact_id";
$acitivty_is_for ="contacts";
$page_url = "contact-profile.php";
}else if ($activity_entity_type_id == "3") {
$acitvity_url = "contact_id";
$acitivty_is_for ="contacts";
$page_url = "contact-profile.php";
}
//Get detailed activity information
//If activity is Email
if ($activity_type_id == "1") {
$email_details = email_activity_details($activity_id);
while ( $email = mysqli_fetch_assoc($email_details)) {
$activity_details = nl2br($email['email_message']);
}
}else if ($activity_type_id == "2") {
$call_details = call_activity_details($activity_id);
while ( $call = mysqli_fetch_assoc($call_details)) {
$activity_details = $call['call_details'];
}
}else if ($activity_type_id == "3") {
$meeting_details = meeting_activity_details($activity_id);
while ( $meeting = mysqli_fetch_assoc($meeting_details)) {
$activity_details = $meeting['meeting_details'];
}
}
//Get creator user info
$user_query = get_user_info($activity_created_by);
while ($user = mysqli_fetch_array($user_query)) {
$activity_created_by = $user['user_full_name'];
}
}
}
?>
Sure:
Create a variable called $activity_store and use the while loop to set the data much in the same way it comes out of the database.
//Get activity base information
$activity_store = array();
while ($activity = mysqli_fetch_array($query)){
$activity_store['activity_related_to_id'] = $activity['activity_related_to_id'];
If you need to store information about each activity pulled from the database separately you could add an index and increment it
//Get activity base information
$activity_store = array();
$i = 0;
while ($activity = mysqli_fetch_array($query)){
$activity_store[$i]['activity_related_to_id'] = $activity['activity_related_to_id'];
...
$i++; //increments $i by 1
}
Just be aware that later in your code when you refer to $activity_type_id you'll now need to refer to '$activity['activity_type_id']`
In terms of returning JSON in php you can use json_encode to encode a variable into a JSON format:
$json_array = json_encode($variable);
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!