WordPress PHP htmlspecialchars(get_field... cannot read arrays? - php

I am working on a WordPress Website/Blog with two main functions.
Create reports.
Compile final report.
People can write reports, selecting the fields they need and publish it. Then at the end of the day, they can "compile" a final report from all of the reports (it concatenate the fields of all reports).
The theme is twentyten (in case it might be useful).
In my function.php file, I concatenate everthing for the final report using a foreach and lines like that:
$Urgences_Environnementales .= htmlspecialchars("<br/>".get_field('Urgences_Environnementales', $idnumber->ID));
$avezvous_regardé_des_indices_de_temps_violent_aujourdhui .= htmlspecialchars(get_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui', $idnumber->ID));
$quelle_est_cette_raison .= htmlspecialchars(get_field('quelle_est_cette_raison', $idnumber->ID));
One line per field, all the same way. After the loop is done, I update the fields:
update_field('Urgences_Environnementales',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($Urgences_Environnementales)), $identificationRapport);
update_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($avezvous_regardé_des_indices_de_temps_violent_aujourdhui)), $identificationRapport);
update_field('quelle_est_cette_raison',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($quelle_est_cette_raison)), $identificationRapport);
Then it's printed for the final report like this (this is a single field):
if(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!=''){
simplebox(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!='', get_field('Urgences_Environnementales'));
}
And for those fields it works perfectly.
My problem is that all my fields composed of arrays (checkboxes that people can select multiple choices using the ACF plugin) are empty in my databse... They appear perfectly in the single reports, but they appear blank in the final report.
As an exemple, this is what I see in my database for a single report for one of my arrays:
a:4:{i:0;s:49:"L’indice d’intensité d’orage violent (STI)";i:1;s:35:"L’indice d’orage violent (TMPV)";i:2;s:34:"Potential Severe Storm Environment";i:3;s:6:"Autres";}
The corresponding field in my final report is empty.
Would someone have an idea on how to read those arrays and record them correctly in my databse? Could I transform them in strings in my foreach loop? Should I do something differently?
If you need more code don't hesitate to ask. I didn't put all my 3 functions (functions.php, report.php, finalreport.php) that I have in my WordPress theme as it would take tons of lines and I'm pretty sure the most important ones are right here. If I'm wrong, I could post the functions.
I searched and searched, but I can't seem to find the answer by myself, so I'm searching for help here.
PS: This is my 1st post, if you have any reccomandations, you can send them to me and I will change my post.
Thank you very much for your help!
PPS: I'm sorry for my english, I'm french, from Montreal, Qc, Canada.

Advanced Custom Fields stores some values as serialized arrays (checkboxes, repeaters, etc). Your code is assuming that you will be getting a string back. As you suggested in your answer, the easiest way to account for this in your current code would be to use the is_array() method to check the type of the returned value, and then another inner loop to handle the summary. This code assumes you just want to concatenate all the values, you could just as easily use another array to make sure they are unique, etc.
// get the value from acf
$value = get_field( 'Urgences_Environnementales', $idnumber->ID );
// if it's already an array, use that, if not make it into an array with a single element
$value_arr = ( is_array( $value ) )? $value : array( $value );
$text = ""; // reset since this is in a loop
// concatenate each checkbox value
foreach ( $value_arr as $val ){
$text .= $val . ', ';
}
// append it to the main summary
$Urgences_Environnementales .= htmlspecialchars( "<br/>". $text );

Related

PHP: Fill array values with corrosponding keys from html meta tags

I have a folder of HTML files, each with meta tags that include dates. I would like to fetch the list of URL's read each one's date meta tag, and finally print the list in order from oldest to youngest, or perhaps youngest to oldest.
I am a beginner at PHP, so I have been able to do a lot of the work myself, but I can't seem to put the various pieces together.
To get a list of the files' URL's into an array is easy enough:
$list = glob('path/*.html');
To fetch the date tag for each individual file is also easy:
$tags=get_meta_tags($file_url);
$date = $tags['date'];
And I can easily sort the array by key using ksort($list); or krsort($list);
However, for the life of me, I cannot figure out how to put this together so that I create a list of URL's, each one with a key from its own date meta tag, and then sort that list.
Any help would be much appreciated, but please keep in mind that I am a complete, absolute beginner at PHP.
Thanks!
You are probably looking for something like this:
<?php
$list = glob('path/*.html');
foreach ($list as $file) {
$tags=get_meta_tags($file);
$result[$tags['date']] = $file;
}
ksort($result);
?>
It computes an array of files using the dates as keys which the list is sorted by.

PHP Extract Single String from List of Values

I need some assistance with php. I have been trying several things for the past several days including str_replace to no avail.
I have a field that may contain from 1 to 20 values, all listed on their own line, there is no html code in that field to separate them and some of the values may have their own spaces in between, so separating by space doesnt work.
What I need is to extract every single string of each line and convert it to code.
<p>For example, my field with values looks like this: </p>
<p><b>lang_fld </b><br>
------
<br>
English<br>
Spanish<br>
German<br>
French</p>
What I have in mind is to extract each line, ex. "English" from that string, and create a line of code like
<img src="images/flags/english.png> English
Basically I want to add the flag graphic to the word
I already tried
echo str_replace('English','<img src="images/flags/english.png>,lang_fld)<br>
...and so on
what I get after going through every single possible value is a bunch error
messages (different every time since I keep making changes - by guessing)
Can someone offer an easier option to do this? Not all 20 values will be in
that areatext field, some may contain just one language, some ten, some all 20,
etc.
Thank you!
Assuming you have all the values on a separate line, you can do explode() on the string to convert it to array of separate items, then loop through the array with foreach and perform any modifications with the single item. After you are done with the items and you would like to get them back together, you can use implode() to combine them into a single string.
A short sample ( you can of course use a for loop, I just prefer foreach here as it shows you better what is happening with the data ):
$text =
"French language
Italian language
English language";
$items = explode( "\n", $text ); // Split by newline ( you can also use "<br>" as separator )
$result = array(); // Modified data will be placed here
foreach ( $items as $item )
{
// Do something with $item
$item = "<img src=\"images/flags/$item.png\"> $item";
$result[] = $item;
}
// Merge them back together
$text = implode("\n", $result);

Return results from form as split array

I'm trying to customize an existing opensource script and ran into a snag. In the processing file, I'm using the following line to retrieve the user's input from a form they submit.
$listingKeywords = $_POST["listingKeywords"];
The user is asked in the form to enter the keywords with a comma in between each one (example: Keyword One, Keyword Two). Within the processing file, I have the following...
$keyword_list = array(
'1'=>"HTML5",
'2'=>"CSS3",
'3'=>"PHP",
);
This is being used later on like so:
foreach ($keyword_list as $key=>$value)
Basically I'm looking for a way to split $listingKeywords by comma and then set the $key via $i++. I know it's simple and I'm just asking for someone to point me in the right direction.
Thanks!
$arr = explode("," $content);
is this what you want?
Just remember to use trim before putting them into a database, people well tend to do use value1, value2, value3

Alter Magento Index Fulltext Search?

I have a unique task that I have been given, and I am in the last leg of it, but this sub-task is proving to be extremely difficult! So you have background: We run a Magento site, and use a custom built SOLR search page. I am using phpSolrClient to parse the Solr XML and return usable result which I then build the search results page from.
The task I have been given is to have an "attribute" in the back end of Magento, lets call that "search_tags". The goal is to be able to insert a tag, and it's weight delimitered by commas:
ie sight^2,hearing^1,smell^3
I would like to edit the code in Magento's fulltext reindex to break apart the string, and insert that tag X of times into the fulltext1_en field. So it would add "sight" twice, "hearing" once, and "smell" three times. This is going to allow us to say, put a blender on the page when someone searches for juicers, even though the term "juicer" or "juice" does not appear in the fulltext1_en string. I have developed the code to pull, split and iterate ... However I am at an stand-still since I don't know what code to edit to include this in my fulltext1_en during the reindex process. If anyone has any experience with editing Magento's Fulltext Reindex, your input would be greatly appreciated! I looked in Indexer.php, but everything in that file is ambiguous at best, so that was no help! Gotta love Magento!
OK for those looking to alter and give "weighted tags" to custom search in Magento using SOLR, I was up all night getting this right, but it works...
First, create a filter in Magento and apply it to all products. I named mine "search_tags".
Next, use the following formula in that filter for a test item:
dude^25,crazyman^25,wierdsearch^25
Each word followed by a carat, and then the weight you want to give it. (This is how many times the word will be repeated and then added to fulltext1_en.)
After that is done, open the following file:
/app/code/core/Mage/CatalogSearch/Model/Mysql4/Fulltext.php
I know it says MySQL4, pay no attention, SOLR uses this index.
About line 500, you will see the following block:
if ($selects) {
$select = '('.join(')UNION(', $selects).')';
$query = $this->_getWriteAdapter()->query($select);
while ($row = $query->fetch()) {
JUST BELOW this block insert the following:
NOTE: Do not use the attribute ID I have listed here, that is unique to my setup. You are going to have to search your database to find this ID. I used JOIN to join eav_attributes with catalog_product_entity_varchar and used SELECT to find attribut_id and value WHERE entity_id = (Insert your product ID here). It's a pain, but it's the only way. This will return all the attributes for that product. Look for the one that has the tags we entered in earlier, and get it's ID. Insert that into the code below.
$attr_val = $row['value']; // Set attr_val so that it can be manipulated in following IF
if ($row['attribute_id'] == 457) { // 457 is the ID of MY search_tags filter, yours WILL be different! It can be found by joining eav_attributes table and catalog_product_entity_varchar and searching for the attribute value and ID where entity_id is X
$input = $row['value']; // Set $input to value of filter
$attr_val = ""; // Create Emtpy string
$pieces = explode( ',', $input ); // Explode filter by comma
foreach ($pieces as $val){
$i=1;
$val = explode( '^', $val); // Explode each "tag" by carat
while ($i <= $val[1]) { // Loop while $i is less than or equal to the number on the right side of the carat
$i++;
$attr_val = $attr_val . " " . $val[0]; // Append $attr_val with the word to the right side of the carat
}
}
}
$result[$row['entity_id']][$row['attribute_id']] = $attr_val; // Modified from Original
After you insert that ... Then comment out the following block.
$result[$row['entity_id']][$row['attribute_id']] = $row['value']; // ORIGINAL BLOCK -- UNCOMMENT -- DO NOT DELETE
Now run a fulltext reindex, and your fulltext1_en should show that you've added "dude", "crazyman", and "weirdsearch" all 25 times! When the index is completed, search for any of the tags in your site search: That item you added the tags to should show up close to, if not the top. Enjoy!

php search and replace

I am trying to create a database field merge into a document (rtf) using php
i.e if I have a document that starts
Dear Sir,
Customer Name: [customer_name], Date of order: [order_date]
After retrieving the appropriate database record I can use a simple search and replace to insert the database field into the right place.
So far so good.
I would however like to have a little more control over the data before it is replaced. For example I may wish to Title Case it, or convert a delimited string into a list with carriage returns.
I would therefore like to be able to add extra formatting commands to the field to be replaced. e.g.
Dear Sir,
Customer Name: [customer_name, TC], Date of order: [order_date, Y/M/D]
There may be more than one formatting command per field.
Is there a way that I can now search for these strings? The format of the strings is not set in stone, so if I have to change the format then I can.
Any suggestions appreciated.
You could use a templating system like Smarty, that might make your life easier, as you can do {$customer_name|ucwords} or actually put PHP code in your email template.
Try a RegEx and preg_replace_callback:
function replace_param($matches)
{
$parts = explode(',',$matches[0]);
//$parts now contains an array like: customer_name,TC,SE,YMD
// do some substitutions and:
return $text;
}
preg_replace_callback('/\[([^\]]+)\]/','replace_param',$rtf);
You can use explode on it to separate them into array values.
For Example:
$customer_name = 'customer_name, TC';
$get_fields = explode(',', $customer_name);
foreach($get_fields as $value)
{
$new_val = trim($value);
// Now do whatever you want to these in here.
}
Sorry if I'm not understanding you.

Categories