My JSON import URL has a field, which sometimes contains a single text or an array.
JSON Array:
wp_u_umlaufart
0 "Personal"
1 "Organisation"
Simple Text:
wp_u_umlaufart "Organisation"
With the function I tried to check if it is an array, if yes then return this as string and if not then just the text.
My Function:
function my_array_convert( $content ) {
if (is_array($content)) {
$converted_arr = implode(",", $content);
return $converted_arr;
} else {
return $content;
}
}
And this is my custom-field:
Unfortunately, only the texts arrive, an array is not returned.
I changed the function to:
function my_array_convert( $content ) {
$obj = json_decode(json_encode($content), true);
if (is_array($obj)) {
$converted_arr = implode(",", $obj);
return $converted_arr;
} else {
return $content;
}
}
WPIMPORT does not output this correctly, I have not found an error so far.
But if i put this in my php Sandbox it will work:
<?php
$content = ["Personal","Organisation"];
$obj = json_decode(json_encode($content), true);
echo is_array($obj) ? 'Yes Array' : 'No Array';
if (is_array($obj)) {
$converted_arr = implode(",", $obj);
echo $converted_arr;
} else {
echo $content;
}
?>
Related
I want to get values using multiple keys.
I have a php code that works for single key but i want to get values for multiple keys. How can i do that?
<?php
$arr=array(
'1'=>'India',
'2'=>'Canada',
'3'=>'United',
'4'=>'China',
'5'=>'London',
'6'=>'New Delhi',
);
$key1='4';
$key2='3';
$key3='4';
echo $arr[$key1, $key2, $key3];
?>
I want output like this in proper order
China
United
China
Thanks in advance.
We have interface ArrayAccess in PHP:
https://www.php.net/manual/en/class.arrayaccess.php
So we can write code as following to support multiple keys( Updated the example from above page ):
You will have to update it to fit your requirements.
<?php
class MultipleKeyArray implements ArrayAccess {
private $container = array();
private $separator = ',';
public function __construct($arr ) {
$this->container = $arr;
}
public function setSeparator($str){
$this->separator = $str;
}
public function offsetSet($offsets, $values) {
$os = explode(',',$offsets);
$vs = explode(',',$values);
$max = max(count($os),count($vs));
for($i=0;$i<$max;$i++){
$offset = $os[$i];
$value = $vs[$i];
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
}
public function offsetExists($offsets) {
$os = explode(',',$offsets);
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
if( !isset($this->container[$offset]) ){
return false;
}
}
return true;
}
public function offsetUnset($offsets) {
$os = explode(',',$offsets);
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
unset($this->container[$offset]);
}
}
public function offsetGet($offsets) {
$os = explode(',',$offsets);
$result = '';
for($i=0;$i<count($os);$i++){
$offset = $os[$i];
$result .= ($i>0 ? $this->separator:'') . (isset($this->container[$offset]) ? $this->container[$offset] : '');
}
return $result;
}
}
$arr=array(
'1'=>'India',
'2'=>'Canada',
'3'=>'United',
'4'=>'China',
'5'=>'London',
'6'=>'New Delhi',
);
$o = new MultipleKeyArray($arr);
$o[] = 'new0';
$o['f,g']='new1,new2';
var_dump(isset($o['f,g']));
var_dump(isset($o['1,2,f']));
var_dump(isset($o['f,not,there']));
echo $o['4,3,4']."\n";
echo $o['2,f,g']."\n";
$o->setSeparator("|");
echo $o['4,3,4']."\n";
Output:
bool(true)
bool(true)
bool(false)
China,United,China
Canada,new1,new2
China|United|China
PHP index cannot take array - you should do that with loop or PHP array function.
First define array of the key you need as:
$keys = [$key1, $key2, $key3];
Now use a foreach loop to echo them as:
foreach($keys as $k)
echo $arr[$k] . PHP_EOL;
And the one-liner:
array_walk($keys, function($k) use ($arr) {echo $arr[$k] . PHP_EOL;});
I have a string that comes from a db: $text=
parameter1=value1
parameter2=value2
otherparemeter=othervalue
I need a function to replace an parameter with a new value, but if parameter does not exist; must to add to string;
Example: updatestring ($text,"parameter1","newvalue"):
Result:
parameter1=newvalue
parameter2=value2
otherparemeter=othervalue
Or: updatestring ($text,"myparameter","myvalue"):
Result:
parameter1=value1
parameter2=value2
otherparemeter=othervalue
myparameter=myvalue
thanks !
Given the format of your input parse_ini_string should work to parse out the data into a structure that can easily be altered and reformated.
Maybe something like this:
$a =<<<EOF
parameter1=value1
parameter2=value2
otherparemeter=othervalue
EOF;
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
}
echo replacevalue($a, "parameter1", "Hello World");
this might work if every paramater and value are on its own line
function updatestring($text, $param1, $param2)
{
if( stristr($text, $param1.'=') ) $text = preg_replace("`$param1=.*\n`iU", "$param1=$param2".PHP_EOL, $text);
else $text .= PHP_EOL.$param1.'='.$param2;
return $text;
}
thanks #Orangepill; I've corrected your function; now it's working
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
} else {
$dat[$k] = $v;
}
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
I am creating this array with the below code:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
}
and i want to check if any item inside the array is LIKE a variable. I have this so far:
if(in_array($data[6], $ignored)) {
but I'm not sure what to do with the LIKE
in_array() doesn't provide this type of comparison. You can make your own function as follows:
<?php
function similar_in_array( $sNeedle , $aHaystack )
{
foreach ($aHaystack as $sKey)
{
if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
{
return true;
}
}
return false;
}
?>
You can use this function as:
if(similar_in_array($data[6], $ignored)) {
echo "Found"; // ^-search ^--array of items
}else{
echo "Not found";
}
Function references:
stripos()
strtolower()
in_array()
Well, like is actually from SQL world.
You can use something like this:
$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
$ignored[] = $ignored2;
if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
//do what you want...
}
}
UPDATE: Well, I found this answer, may be it's what you need:
Php Search_Array using Wildcard
Here is a way to do it that can be customized fairly easily, using a lambda function:
$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');
while ($word = array_shift($otherwords)) {
print_r(array_filter($words, like_word($word)));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
http://codepad.org/yAyvPTIq
To add different checks, simply add more conditions to the return. To do it in a single function call:
while ($word = array_shift($otherwords)) {
print_r(find_like_word($word, $words));
}
function find_like_word($word, $words) {
return array_filter($words, like_word($word));
}
function like_word($word) {
return create_function(
'$a',
'return strtolower($a) == strtolower(' . $word . ');'
);
}
My problem is basically, I will be trying to get data from a table called, 'rank' and it will have data formatted like, "1,2,3,4,5" etc to grant permissions. So Basically I am trying to make it an array and find if one number is there in the array. Basically making it an array is not working. How would I get this done? Here is my code below:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = array($ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>
This code returns false, while it should return true. This is just a basic algorithm.
The print_r Display:
Array ( [0] => 1,2,3,4,5 )
If you know for sure your delimiter is a comma, try this:
$ranks = explode(',',$rank);
where $rank is your string.
That's simple, you explode the $ranks variable by comma ,:
$ranks = "1,2,3,4,5";
$uRanks = explode(',',$ranks);
//$uRanks would now be array(1,2,3,4,5);
if(in_array($rank, $uRanks)) {
//..rest of your code
You should:
$uRanks = explode(',', $ranks);
instead of:
$uRanks = array($ranks);
to make this as array.
Problem solved. I used the explode function instead like this:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = explode(',', $ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>
How to search text using php?
Something like:
<?php
$text = "Hello World!";
if ($text contains "World") {
echo "True";
}
?>
Except replacing if ($text contains "World") { with a working condition.
In your case you can just use strpos(), or stripos() for case insensitive search:
if (stripos($text, "world") !== false) {
echo "True";
}
What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:
if(strstr($text, "world")) {/* do stuff */}
If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.
Implementation of the vector space model in PHP
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort fro high to low
arsort($similar_documents);
}
return $similar_documents;
}
IN YOUR CASE
$query = 'world';
$corpus = array(
1 => 'hello world',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.79248125036058
)
MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES
$query = 'hello world';
$corpus = array(
1 => 'hello world how are you today?',
2 => 'how do you do world',
3 => 'hello, here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.74864218272161
[2] => 0.43398500028846
)
from How do I check if a string contains a specific word in PHP?
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
$user = strstr($email, '#', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
http://php.net/manual/en/book.strings.php
in my opinion strstr() is better than strpos(). because strstr() is compatible with both PHP 4 AND PHP 5. but strpos() is only compatible with PHP 5. please note that part of servers have no PHP 5
/* https://ideone.com/saBPIe */
function search($search, $string) {
$pos = strpos($string, $search);
if ($pos === false) {
return "not found";
} else {
return "found in " . $pos;
}
}
echo search("world", "hello world");
Embed PHP online:
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/saBPIe" ></iframe>
The best solution is my method:
In my method, only full words are detected,But in other ways it is not.
for example:
$text='hello world!';
if(strpos($text, 'wor') === FALSE) {
echo '"wor" not found in string';
}
Result: strpos returned true!!! but in my method return false.
My method:
public function searchInLine($txt,$word){
$txt=strtolower($txt);
$word=strtolower($word);
$word_length=strlen($word);
$string_length=strlen($txt);
if(strpos($txt,$word)!==false){
$indx=strpos($txt,$word);
$last_word=$indx+$word_length;
if($indx==0){
if(strpos($txt,$word." ")!==false){
return true;
}
if(strpos($txt,$word.".")!==false){
return true;
}
if(strpos($txt,$word.",")!==false){
return true;
}
if(strpos($txt,$word."?")!==false){
return true;
}
if(strpos($txt,$word."!")!==false){
return true;
}
}else if($last_word==$string_length){
if(strpos($txt," ".$word)!==false){
return true;
}
if(strpos($txt,".".$word)!==false){
return true;
}
if(strpos($txt,",".$word)!==false){
return true;
}
if(strpos($txt,"?".$word)!==false){
return true;
}
if(strpos($txt,"!".$word)!==false){
return true;
}
}else{
if(strpos($txt," ".$word." ")!==false){
return true;
}
if(strpos($txt," ".$word.".")!==false){
return true;
}
if(strpos($txt," ".$word.",")!==false){
return true;
}
if(strpos($txt," ".$word."!")!==false){
return true;
}
if(strpos($txt," ".$word."?")!==false){
return true;
}
}
}
return false;
}