I am trying to write a function in PHP, but being a novice I am finding it a bit difficult to do so. I have an array which looks like
[{"x":"12345","y":"john"},{"x":"12345","y":"stars"}]
The function which I am writing is
function getCSV($x)
{
// Now I want to pass the $x which in the above array is 12345 and get "john,stars" as output
}
Are there any methods available in PHP that can do this, or what would be the best approach to get it?
That looks like a json to me
[{"x":"12345","y":"john"},{"uid1":"12345","uid2":"stars"}]
function getCSV($x)
{
$arr = json_decode($x);
echo $arr[0]->y . ', ' . $arr[1]->uid2;
}
This looks horrible, but withouth further explanation is the only thing that works
EDIT - after your edit
function getCSV($x)
{
$arr = json_decode($x);
$y = array();
foreach($arr as $obj){
$y[] = $obj->y;
}
return implode(',', $y);
}
here is a working pad http://codepad.org/HzttdmjW
Related
Hi I'm struggling trying to perform a calculation in Laravel 7.
I have a variable like $val = '1000*2'; and I'm looking for a helper function or related to perform it.
eval($val) does not seem to function in a proper way. I just want a function that results in 2000.
TIA
If you only have to deal with multiplication, you could try something like this.
$val = '1000*2';
$parts = explode('*', $val);
$res = array_reduce($parts, function($carry, $item) {
return $carry * $item;
}, 1);
echo $res;
I do not advise using eval() to perform calculations with values passed by a user.
If you really want to receive the value at all costs, you can do something like this:
$val = "echo 1000 * 2;";
eval ($val);
Or
$val = eval("return 1000 * 2;");
echo $val;
You can find more information in the documentation.
https://www.php.net/manual/pt_BR/function.eval.php
Guys this library helped me https://github.com/mossadal/math-parser
$parser = new StdMathParser();
$AST = $parser->parse($val);
Then I could access it with $AST->getValue().
Thank you!!
I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)
How can I change the code below so each part is added together in a little bunch instead of smushed together? If a little part that appears on the screen is 123, it should add 12+3 and display 15 instead of 123. I have tried sum_array and other things but it won't work to add PARTS with other PARTS in little bunches. I can only get it to display smushed together results how it is below, or add the wrong parts or the whole thing other ways.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination . "<br>";
}
return $combinationsarray;
}
It looks like
$combination.=$array[$j];
is your problem . in PHP is used for String Concatenation and not math. Because PHP is a loosely data typed language you are telling PHP to take the String value of $array[$j] and ".=" (append) it to $combination giving you the 12 .= 3 == "123" problem and not 15 like what you want. You should try += instead.
If I understand what you're trying to do, I think you want to use addition + instead of concatination . in the following line:
if($binary[$j]=="1")
$combination += $array[$j];
I have now got a working regex string for the below needed criteria:
a one line php-ready regex that encompasses a number of keywords, and keyterms and will match at least one of them.
For example:
Keyterms:
apple
banana
strawberry
pear cake
Now if any of these key terms are found then it returns true. However, to add a little more difficulty here, the pear cake term should be split as two keywords which must both be in the string, but need not be together.
Example strings which should return true:
A great cake is made from pear
i like apples
i like apples and bananas
i like cakes made from pear and apples
I like cakes made from pears
The working regex is:
/\bapple|\bbanana|\bstrawberry|\bpear.*?\bcake|\bcake.*?\bpear/
Now I need a php function that will create this regex on the fly from an array of keyterms. The stickler is that a keyterm may have any number of keywords within that key. Only on of the keyterms need be found, but multiple can be present. As above all of the the words within a keyterm must appear in the string in any order.
I have written a function for you here:
<?php
function permutations($array)
{
$list = array();
for ($i=0; $i<=10000; $i++) {
shuffle($array);
$tmp = implode(',',$array);
if (isset($list[$tmp])) {
$list[$tmp]++;
} else {
$list[$tmp] = 1;
}
}
ksort($list);
$list = array_keys($list);
return $list;
}
function CreateRegex($array)
{
$toReturn = '/';
foreach($array AS $value)
{
//Contains spaces
if(strpos($value, " ") != false)
{
$pieces = explode(" ", $value);
$combos = permutations($pieces);
foreach($combos AS $currentCombo)
{
$currentPieces = explode(',', $currentCombo);
foreach($currentPieces AS $finallyGotIt)
{
$toReturn .= '\b' . $finallyGotIt . '.*?';
}
$toReturn = substr($toReturn, 0, -3) . '|';
}
}
else
{
$toReturn .= '\b' . $value . '|';
}
}
$toReturn = substr($toReturn, 0, -1) . '/';
return $toReturn;
}
var_dump(CreateRegex(array('apple', 'banana', 'strawberry', 'pear cake')));
?>
I got the permutations function from:
http://www.hashbangcode.com/blog/getting-all-permutations-array-php-74.html
But I would recommend to find a better function and use another one since just at first glance this one is pretty ugly since it increments $i to 10,000 no matter what.
Also, here is a codepad for the code:
http://codepad.org/nUhFwKz1
Let me know if there is something wrong with it!
How to find memory used by an object in PHP? (c's sizeof). The object I want to find out about is a dictionary with strings and ints in it so it makes it hard to calculate it manually. Also string in php can be of varied length depending on encoding (utf8 etc) correct?
You could use memory_get_usage().
Run it once before creating your object, then again after creating your object, and take the difference between the two results.
To get an idea about the objects size, try
strlen(serialize($object));
It is by no means accurate, but an easy way to get a number for comparison.
If you need to know the size of an already created object or array, you can use the following code to find it out.
<?php
function rec_copy($src) {
if (is_string($src)) {
return str_replace('SOME_NEVER_OCCURING_VALUE_145645645734534523', 'XYZ', $src);
}
if (is_numeric($src)) {
return ($src + 0);
}
if (is_bool($src)) {
return ($src?TRUE:FALSE);
}
if (is_null($src)) {
return NULL;
}
if (is_object($src)) {
$new = (object) array();
foreach ($src as $key => $val) {
$new->$key = rec_copy($val);
}
return $new;
}
if (!is_array($src)) {
print_r(gettype($src) . "\n");
return $src;
}
$new = array();
foreach ($src as $key => $val) {
$new[$key] = rec_copy($val);
}
return $new;
}
$old = memory_get_usage();
$dummy = rec_copy($src);
$mem = memory_get_usage();
$size = abs($mem - $old);
?>
This essentially creates a copy of the array structure and all of its members.
A not 100% accurate, but still working version is also:
<?php
$old = memory_get_usage();
$dummy = unserialize(serialize($src));
$mem = memory_get_usage();
$size = abs($mem - $old);
Hope that helps for cases where the object is already build.
This method converts the array to a json string and determines the length of that string. The result should be fairly similar to the size of the array (both will have delimiters to partition members of the array or the stringified json)
strlen(json_encode(YourArray))
this method could be help you:
function getVariableUsage($var) {
$total_memory = memory_get_usage();
$tmp = unserialize(serialize($var));
return memory_get_usage() - $total_memory;
}
$var = "Hey, what's you doing?";
echo getVariableUsage($var);
https://www.phpflow.com/
I don't know that there is a simple way to get the size of an object in PHP. You might just have to do an algorith that
Counts the ints
Multiplies number of ints by size of an int on hard disk
Convert characters in strings to ASCII and
Multiply the ASCII values by how much they take up on disk
I'm sure there is a better way, but this would work, even though it would be a pain.