I really need some help with this code and I'm not that good at PHP.
Here is the code:
function projectAttr($number){
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls= (bool) $clerk->getSetting( "clean_urls", 1 );
$getTags = $clerk->query_select ( "projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC" );
while ( $tag= $clerk->query_fetchArray( $getTags ) )
{
$tagset = explode('; ', $tag['tag']);
}
return html_entity_decode($tagset[$number]);
}
The code explodes a string and puts it in a array, that I can get by projectAttr(0). But I want to be more specific in what I want to get from the string.
This is my string:
size='large'; caption='short text about post/project'; bgcolor='black'; color='white';
What I want is, if I write projectAttr(size) it should return the value large and so forth.
Is that even possible?
Thanks, Peter
I'll answer specifically to the explode you want. You should modify your projectAttr function to look this this:
$items = explode('; ', $string);
$attr = array();
foreach($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '',$val);
}
Which returns
Array (
[size] => large
[caption] => short text about post/project
[bgcolor] => black
[color] => white
)
EXAMPLE DEMO
So modify your function to look like this:
function projectAttr($name) {
global $clerk, $project;
$projectid = $project['id'];
$tags = array();
$cleanUrls = (bool) $clerk->getSetting("clean_urls", 1);
$getTags = $clerk->query_select("projects_to_tags", "DISTINCT tag", "WHERE projectid='$projectid' ORDER BY id ASC");
while ($tag = $clerk->query_fetchArray($getTags)) {
$items = explode('; ', $string);
$attr = array();
foreach ($items as $item) {
list($key, $val) = explode('=', $item);
$attr[$key] = str_replace(array("'", ""), '', $val);
}
}
return html_entity_decode($attr[$name]);
}
And that should allow you to call it like this:
projectAttr('size');
try
function projectAttr($number){
$str= "size='large'; caption='short text about post/project'; bgcolor='black'; color='white';";
$r = explode('; ', $str);
foreach($r as $k=>$v) {
$attr = explode('=', $v);
$projectAttr[$attr[0]] = str_replace("'", "", $attr[1]);
}
return html_entity_decode($projectAttr[$number]);
}
echo projectAttr('size'); // large
Related
I'm fairly new to PHP and I have a question.
I'm trying to make a function that adds tags to a text.
My function works but the order of the tags in the array returned is wrong.
How can I change the order, please
Thanks for any help.
<?php
$tags = [
'animals' => ['cat', 'dog', 'horse', 'ferret'],
'nature' => ['walk', 'outdoor', 'tree', 'plant']];
function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
$tagArray = [];
foreach ($tags as $tag => $value) {
if (array_intersect( $value, $arrayT )) {
$tagArray[] = $tag;
}
} return $tagArray;
}
$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res); // returns ['animals', 'nature'] but I'm trying to get ['nature', 'animals']
If you want to get 'nature' first, because 'walk' comes before 'horse', you need to iterate over the words first, not over the tags.
$tags = [
'animals' => ['cat', 'dog', 'horse', 'ferret'],
'nature' => ['walk', 'outdoor', 'tree', 'plant'],
];
function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
$tagArray = [];
foreach ($arrayT as $word) {
// find tag for this word
foreach ($tags as $cat => $values) {
if (in_array($word, $values)) {
// append the tag to the list
$tagArray[] = $cat;
}
}
}
// remove duplicates
return array_unique($tagArray);
}
$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res);
Output :
array(2) {
[0]=>
string(6) "nature"
[1]=>
string(7) "animals"
}
EDIT
As #GeorgeGarchagudashvili mentionned, the code could be optimized by preparing an array for comparison. Here is a way :
function getTags(string $text, array $tags): array
{
$lowerC = strtolower($text);
$str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
$arrayT = explode(" ", $str);
// Prepare tags for searching
$searchTags = [];
foreach ($tags as $cat => $values) {
foreach ($values as $word) {
$searchTags[$word] = $cat;
}
}
$tagArray = [];
foreach ($arrayT as $word)
{
// find tag for this word
if (isset($searchTags[$word]))
{
// append the tag to the list
$tagArray[] = $searchTags[$word];
}
}
// remove duplicates
return array_unique($tagArray);
}
Hello i have a script that extract company names from a string. I want that the extracted names to be converted to php variable. So for example first result Real Coffee Sweeden must be converted to $RealCoffeeSweeden = 0 so i can assign a value to it
$test='/showname/0406741848 : Real Coffee Sweeden
/showname/0406741849 : Healthzone SE
/showname/16133663413 : FREE
/showname/16133663414 : RadioPlantes Canada
/showname/16133663417 : Dealsoftoday.Eu Canada
/showname/16136995593 : FREE
/showname/16136995594 : Club White Smile Canada
/showname/16138007442 : FREE
/showname/16138007547 : Mybitwave.com Canada
/showname/16465596150 : BABY
/showname/16465696956 : FREE
/showname/16465696957 : FREE
/showname/16467419944 : Mybitwave.com UK
/showname/16469181975 : FREE
/showname/21501350 : SecureSurf.EU NO
/showname/21501351 : FileCloud365 Norwegian
/showname/21501352 : FREE
/showname/21501353 : RadioPlantes Norwegian
';
$myRows= explode("\n", $test);
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$result[] = $pieces[1];
}
foreach ($result as $res){
$res // covert to php variable
//example: $RealCoffeeSweeden = 0;
}
You can try it this way
$my_array = explode("\n", $test);
foreach($my_array as $key => $value {
$my_string = explode(':', $value)
${str_replace(' ','', $my_string[1])} = $my_string;
echo $$my_string;
}
You should use an array for that. But if you want to do it the way you write, you can simply do something like that:
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$res = str_replace(' ', '', $pieces[1]); // replace whitespaces for valid names
$$res = 0; // note the double dollar signs
}
If you want to use an array tho, do something like this:
$result = [];
foreach( $myRows as $key => $value) {
$pieces = explode(":", $value);
$key = str_replace(' ', '', $pieces[1]);
$result[$key] = 0;
}
According to your comment, change second last line in the foreach loop with following:
$res = str_replace(' ', '', $res) . '_f';
I am working on a latin website that holds some information in a string this way:
nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is
I would like to turn this information into an array like this
array(
'nominative'=>array(
0=>array('us','a','um')
),
'genitive'=>array(
0=>'i'
)
'dative'=>array(
1=>'is'
)
'ablative'=>array(
1=>'is'
)
)
My current code looks like this
//turn into array for each specification
$specs=explode(';',$specificities);
foreach($specs as $spec):
//turn each specification into a consecutive array
$parts=explode(':',$spec);
//turn multiple value into array
foreach($parts as &$value)
if(strpos($value,',')!==false)
$value=explode(',',$value);
//imbricate into one other
while(count($parts)!==1):
$val=array_pop($parts);
$key=array_pop($parts);
if(is_array($key)):
foreach($key as $k)
$parts[$k]=$val;
else:
$parts[$key]=$val;
endif;
endwhile;
endforeach;
I'm stuck. Help.
Edit: Thanks for the quick responses everybody!
The response I preferred was from CaCtus. I modified it to add flexibility but it was the most useful.
For those interested, here is the new code:
$parts=explode(';','nominative:0:er,ra,rum;genitive:0:i;dative,ablative:1:is;root:r;');
if(!empty($parts)&&!empty($parts[0])):
foreach($parts as $part):
$subpart=explode(':',$part);
$keys=explode(',',$subpart[0]);
foreach($keys as $key):
#$vals=(strpos($subpart[2],',')!==false)
?explode(',',$subpart[2])
:$subpart[2];
$final=(is_null($vals))
?$subpart[1]
:array($subpart[1]=>$vals);
endforeach;
endforeach;
endif;
$string = 'nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is';
$finalArray = array();
// Separate each specification
$parts = explode(';', $string);
foreach($parts as $part) {
// Get values : specification name, index and value
$subpart = explode(':', $part);
// Get different specification names
$keys = explode(',', $subpart[0]);
foreach($keys as $key) {
if (preg_match('#,#', $subpart[2])) {
// Several values
$finalValues = explode(',', $subpart[2]);
} else {
// Only one value
$finalValues = $subpart[2];
}
$finalArray[$key] = array(
$subpart[1] => $finalValues
);
}
}
Would something a little simplier work?
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch; }
$input = "0:us,a,um;genitive:0:i;dative,ablative:1:is";
$exploded = multiexplode(array(",",":",";"),$input);
$test = array(
'nominative'=>array(0=>array($exploded[1],$exploded[2],$exploded[3])),
$exploded[4]=>array(0=>$exploded[6]),
$exploded[7]=>array(1=>$exploded[10]),
$exploded[8]=>array(1=>$exploded[10]) );
print_r($test);
Just another alternative:
$specificities = "nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is";
$specificities = trim($specificities, ";") . ";"; //mandatory a trailing ;
$pattern = "/(?<types>[a-z\,]+):(?<ids>\d):(?<values>.*?);/";
preg_match_all($pattern, $specificities, $matches, PREG_SET_ORDER);
$result = array();
array_map(function($item) use (&$result)
{
$types = explode("," , $item['types']);
if(count($types) == 1)
{
$result[$item['types']] = array(
$item['ids'] => explode("," , $item['values'])
);
}
else
{
foreach ($types as $type)
{
$result[$type] = array(
$item['ids'] => explode("," , $item['values'])
);
}
}
}, $matches);
var_dump($result);
I have the following function which works fine.
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$result[$object->id] = $object->first_name . ' ' . $object->last_name;
}
return $result;
}
However, I would like to pass in an array to $items, and have that exploded, so that I dont have to specify first_name and last_name manually.
If $item was only a single value (and not an array), then it would be simple:
$result[$object->id] = $object->$item;
But I have no idea how to make this work if $items contains multiple values and I want to join them with a space. Something like, the following, but I need to get the $object in there
$items = array('first_name', 'last_name');
$result[$object->id] = implode(' ', $items);
Do I get you right that you`d like to use the strings in $item as property-names of $object?
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$valuesToAssign = array();
foreach ($items as $property) {
$valuesToAssign[] = $object->$property;
}
$result[$object->id] = implode(' ', $valuesToAssign);
}
return $result;
}
I have no idea to avoid the second foreach, but that gives you the desired result.
Not sure if I got you right, but how about this:
function foo($objects, $items = array()) {
$result = array();
$keys = array_flip($items);
foreach ($objects as $object) {
// Cast object to array, then omit all the stuff that is not in $items
$values = array_intersect_key((array) $object, $keys);
// Glue the pieces together
$result[$object->id] = implode(' ', $values);
}
return $result;
}
Demo: http://codepad.viper-7.com/l8vmGr
This is my $data variable:
cv = 1,2,3,4,5:::cpt = 4,5 ...
Now I need some function, where I can add the number as param (number will be $data number value).
for example.
function getPermission($id) {
... return $something;
}
Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.
So, to be clear:
if I call the function like this:
echo getPermission(4); output will be "cv" and "cpt".
but if I call it this way:
echo getPermission(1);
it'll only output "cv" because number (1) is located in the cv key.
Hope you guys understand, feel free to ask if something aren't clear enough.
$str = 'cv = 1,2,3,4,5:::cpt = 4,5';
$tmp = explode(':::', $str);
$data = array();
foreach ($tmp as $arr) {
$tokens = explode(' = ', $arr);
$data[$tokens[0]] = explode(',', $tokens[1]);
}
print_r(getPermission(4, $data));
print_r(getPermission(1, $data));
function getPermission($id, $data) {
$out = array();
foreach ($data as $key => $arr) {
if (in_array($id, $arr)) $out[] = $key;
}
return $out;
}