I wrote a javascript function which takes in a string and parses it as an associative array.
function getValues(string){
var array_values = new Array();
var pairs_array = string.split('\n');
if(pairs_array[0] == 'SUCCESS'){
window.success = true;
}
for(x=1; x< pairs_array.length; x++){
var parsedValue = '';
//console.log(pairs_array[x] + "<br>");
var pair = pairs_array[x].split('=');
//console.log(pair[1]);
var variable = pair[0];
if(pair[1]){
var value = pair[1];
for(i=0; i< value.length; i++){
var character = value.charAt(i);
if(character == '+'){
parsedValue = parsedValue + character.replace('+', ' ');
}else{
parsedValue = parsedValue + value.charAt(i);
}
}
array_values[variable] = decodeURIComponent(parsedValue);
}else{
array_values[variable] = '';
}
}
return array_values;
}
Then the function is called on the string window.name_value_pairs as follows
var array_callback = getValues(window.name_value_pairs);
for(x in array_callback){
console.log("call" + x + " " + array_callback[x]);
}
Works fine. Now i have been trying to write the function in php because i would prefer it on the server side but it is not working out. I'm not sure if the array values ar getting pushed onto the array because nothing gets returned. heres the php code i have tried:
Note: $results_values is a string
$result_values = $_REQUEST['result_values'];
echo "php array " . getValuesPhp($result_values);
function getValuesPhp($string){
$array_values = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$variable = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
for($i=0; $i< strlen($value); $i++){
$character = $value[$i];
//echo "char \n" . $character;
if(strpos($character, '+') !== false){
//echo "plus";
$parsedValue .= str_replace('+', ' ', $character);
}else{
//echo "hi2";
$parsedValue .= $value[$i];
}
}
echo "\n var " . $variable;
echo "\n parsed " . $parsedValue;
$array_values['" . $variable . "'] = $parsedValue;
//echo "arrayValues " . $array_values['" . $variable . "'];
//array_push($GLOBALS[$array_values]['" . $variable . "'], $parsedValue);
}else{
$array_values['" . $variable . "'] = '';
//array_push($GLOBALS[$array_values]['" . $variable . "'], '');
}
}
//echo "array payment stat" . $array_values['payment_status'];
return $array_values;
}
note: where it says $array_values['" . $variable . "'] this does print out the write result as it goes through the loop however it seems like the array elements are not being added to the array as nothing is returned at the end.
Thanks for any help
Sarah
Update:
#ChrisWillard I would like to return an associative array from the string. the string is in the format where each line is in the form key=value .. it is actually the string which comes back from a paypal pdt response. For example:
SUCCESS
mc_gross=3.00
protection_eligibility=Eligible
address_status=confirmed
item_number1=3
tax=0.00
item_number2=2
payer_id=VWCYB9FFJ
address_street=1+Main+Terrace
payment_date=14%3A26%3A14+May+22%2C+2014+PDT
payment_status=Completed
charset=windows-1252
address_zip=W12+4LQ
mc_shipping=0.00
mc_handling=0.00
first_name=Sam
address_country_code=GB
address_name=Sam+Monks
custom=
payer_status=verified
business=mon%40gmail.com
address_country=United+Kingdom
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=Wolverhampton
payer_email=monks%40gmail.com
mc_shipping1=0.00
mc_shipping2=0.00
tax1=0.00
tax2=0.00
txn_id=3PX5572092U
payment_type=instant
last_name=Monks
address_state=West+Midlands
item_name1=Electro
receiver_email=mon%40gmail.com
item_name2=Dub
quantity1=1
quantity2=1
receiver_id=WHRPZLLP6
pending_reason=multi_currency
txn_type=cart
mc_gross_1=1.00
mc_currency=USD
mc_gross_2=2.00
residence_country=GB
transaction_subject=
payment_gross=3.00
thanks for all your answers and help. it was a combination of two things that caused it to not print.. firstly my silly syntax error (being just new at programming haha I wont go into the logic i had behind this but it did make sense to me at the time haha) $array_values['" . $variable . "'] = $parsedValue; changed to this:
$array_values[$variable] = $parsedValue;
it was also the line
echo "php array" . getValuesPhp($result_values); that caused it not to print.
when i changed this to
print_r(getValuesPhp($result_values)); it printed perfect thanks to #ChrisWillard for this. So here is my final code. A combination of #ChrisWillard answer and #Mark B and #Jdo answers. I also wanted to check first if pair[1] existed and go through each character of pair[1] changing any '+' to a space ' ' if it existed so that it could be read by the user. Now i have found the function to do this for me haha. I'm sure it is not new information for a lot of you but for anyone who doesn't know it is urldecode so you can see below ive commented out the loop that i did not need (going through the characters of the string changing the plus value) and instead ive written: $finished_array[$key] = urldecode($value); thanks for all your help.
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true;
//echo "TRUE";
}
for($x=1; $x< count($pairs_array); $x++){
$parsedValue = '';
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
if(isset($pair[1])){
$value = $pair[1];
//for($i=0; $i< strlen($value); $i++){
//$character = $value[$i];
//if(strpos($character, '+') !== false){
//$parsedValue .= str_replace('+', ' ', $character);
//}else{
//$parsedValue .= $value[$i];
//}
//}
$finished_array[$key] = urldecode($value);
}else{
$finished_array[$key] = '';
}
}
return $finished_array;
}
This is totally non-sensical:
$array_values['" . $variable . "'] = $parsedValue;
You're literally using " . $variable . " as your array key - remember that '-quoted strings do NOT expand variables.
Why not just
$array_values[$variable] = $parsedValue
From what I can gather, this should get you what you need:
$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));
function getValuesPhp($string){
$finished_array = array();
$pairs_array = explode("\n",$string);
if($pairs_array[0] == 'SUCCESS'){
$success = true; ////Not sure what you're trying to do here
}
for($x=1; $x< count($pairs_array); $x++) {
$pair = explode("=",$pairs_array[$x]);
$key = $pair[0];
$value = $pair[1];
$finished_array[$key] = $value;
}
return $finished_array;
}
Related
I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>
I'm new to PHP and I've encountered an issue that is driving me crazy. Perhaps someone here can let me know what I'm doing wrong.
I have a from that a user fills out. The below script is using the date entered into the mysql database to generate json data:
<?php
include("../includes.php");
$sq = new SQL();
$TableName = "permissions";
$Fields = $_POST["Fields"];
$FieldsSTR = "`" . str_replace("*;*","`,`", $Fields) . "`";
$Join = "AND";
$Start = 0;
$Limit = $_POST["Limit"];
if($Limit == "")$Limit = 1000;
$Where = $_POST["Where"];
$WhereSTR = "";
if($Where !== "")$WhereSTR = str_replace("*;*"," $Join ", $Where);
$q = "SELECT $FieldsSTR FROM `$TableName` $WhereSTR";
$data = $sq->sqlQuery($q);
if(sizeof($data)>0)array_shift($data);
header("Content-Type: application/json");
echo "[";
foreach($data as $k=>$line){
echo "[";
echo "\"" . str_replace("*;*","\",\"",$line) . "\"";
echo "]";
if($k < sizeof($data) - 1)echo ",";
}
echo "]";
exit;
?>
The problem that I'm having is that it has stopped working. One day it's fine and the next day it's not working. I'm thinking that maybe the cause of this problem is that crazy user data has been entered into the database. In my foreach statement I tried to replace the ";" with a "" tag, but that didn't work.
Has anyone encountered this issue before? Perhaps someone can point me in the right direction!
Thanks
Jason
Thanks everyone for your input. I was able to stumble on an fix to my immediate problem. I changed my foreach loop to the following:
foreach($data as $k=>$line){
$parts = explode("*;*",$line);
$NEWLINE = array();
for($i = 0;$i < sizeof($parts);$i++){
$value = $parts[$i];
$value = str_replace("\r","<br>",str_replace("\n","<br>",$value));
$NEWLINE[] = "\"" . $value . "\"";
}
$FINDATA[] = "[" . implode(",",$NEWLINE) . "]";
}
But I will now look into into using json_encode() as mentioned in the comments.
Thanks,
Jason
I have an if statement here it works perfect for what I want it to do. It loops through some values e.g. sop_01 to sop_06 and writes their output separated with a br. I would like to know if this is the most efficient way of writing this code as to me it does not seem very efficient e.g. what happened if the values went from sop_01 to sop_1000 you would not write this out manually?
if (TRIM($row['sop_01']) <> null){
$sop = TRIM($row['sop_01']);
if (TRIM($row['sop_02']) <> ""){
$sop = $sop . "<br>" . TRIM($row['sop_02']);
if (TRIM($row['sop_03']) <> ""){
$sop = $sop . "<br>" . TRIM($row['sop_03']);
if (TRIM($row['sop_04']) <> ""){
$sop = $sop . "<br>" . TRIM($row['sop_04']);
if (TRIM($row['sop_05']) <> ""){
$sop = $sop . "<br>" . TRIM($row['sop_05']);
if (TRIM($row['sop_06']) <> ""){
$sop = $sop . "<br>" . TRIM($row['sop_06']);
}
}
}
}
}
} else { $sop = "hello world"; }
A little background info; if sop_01 is null then all the other values will be null
if sop_01 is <> null there is a possibility the other values are either “” or have a value
if sop_02 is empty it is not null it is "" (Due to how the data is stored in the database)
Please let me know if I can provide any further information
Bepster
First create a array containing all keys to use. Then manipulate the array this way:
// create array with "allowed" keys, btw. you can convert it into a loop :)
$keys = array_flip(array('sop_01', 'sop_02', 'sop_03', 'sop_04', 'sop_05', 'sop_06'));
// take only items with keys of array $keys
$sop = array_intersect_key($row, $keys);
// will call the function `trim` on every item of the array
$sop = array_map('trim', $sop);
// will remove all empty strings
$sop = array_filter($sop);
// will join all items of the array with a `<br>` between them.
$sop = implode('<br>', $sop);
if you need this Hello world string if row is "empty" you could add this line:
$sop = empty($sop) ? 'Hello world' : $sop;
To create the $keys array with a loop use this
$keys = array();
$i = 1;
while(isset($row['sop_'.$i])){
$keys['sop_'.$i++] = true;
}
It will create a array, depending on how many "fields" matching the pattern sop_%d (in a row starting from 1) part of the $row array. (Is this sentence correct?)
You can try this with some inbuilt PHP functions -
$row = array_map('trim', $row); // trim all the values present
if ($row['sop_01'] <> null) {
$temp = array_filter($row); // will remove all the empty, null ...
$sop = implode('<br>', $temp); // concatenate the values with <br>
} else {
$sop = "hello world";
}
assuming $row would contain those values (strings) only. If not you can store them in an array and do the rest.
array_filter(), array_map()
Use for loop and built index dynamically.
$start = 1;
$end = count($row);
$sop = '';
for ($i = $start; $i <= $end; $i++) {
$num = ($i < 10) ? '0' . $i : $i;
$index = 'sop_' . $num;
if (TRIM($row[$index]) <> "") {
$sop = $sop . "<br>" . TRIM($row[$index]);
}
}
this code will work for 1000 or more values properly -
<?php
$rows = count($row);
$i = 2;
$sop = "";
if (TRIM($row['sop_01']) <> null){
$sop = $sop . TRIM($row['sop_01']);
get_soap($rows, $i, $sop);
} else { $sop = "hello world"; }
function get_soap($rows, $i, $sop){
if($i <= $rows){
if (TRIM($row['sop_'.$i]) <> "")
$sop = $sop . "<br>" . TRIM($row['sop_'.$i]);
$i++;
get_soap($rows ,$i, $sop);
}
}
?>
How can I convert my amount into words? I tried this code but it gave me this error when I call the function.
Fatal error: Call to undefined function Convert()
Did I do something wrong?
if (isset($_REQUEST["generate"])) {
$amount=$_POST["amount"];
$amountinword=Convert($amount);
}
<?php
Class Convert {
var $words = array();
var $places = array();
var $amount_in_words;
var $decimal;
var $decimal_len;
function Convert($amount, $currency="Pesos") {
$this->assign();
$temp = (string)$amount;
$pos = strpos($temp,".");
if ($pos) {
$temp = substr($temp,0,$pos);
$this->decimal = strstr((string)$amount,".");
$this->decimal_len = strlen($this->decimal) - 2;
$this->decimal = substr($this->decimal,1,$this->decimal_len+1);
}
$len = strlen($temp)-1;
$ctr = 0;
$arr = array();
while ($len >= 0) {
if ($len >= 2) {
$arr[$ctr++] = substr($temp, $len-2, 3);
$len -= 3;
} else {
$arr[$ctr++] = substr($temp,0,$len+1);
$len = -1;
}
}
$str = "";
for ($i=count($arr)-1; $i>=0; $i--) {
$figure = $arr[$i];
$sub = array(); $temp="";
for ($y=0; $y<strlen(trim($figure)); $y++) {
$sub[$y] = substr($figure,$y,1);
}
$len = count($sub);
if ($len==3) {
if ($sub[0]!="0") {
$temp .= ((strlen($str)>0)?" ":"") . trim($this->words[$sub[0]]) . " Hundred";
}
$temp .= $this->processTen($sub[1], $sub[2]);
} elseif ($len==2) {
$temp .= $this->processTen($sub[0], $sub[1]);
} else {
$temp .= $words[$sub[0]];
}
if (strlen($temp)>0) {
$str .= $temp . $this->places[$i];
}
}
$str .= " " . $currency;
if ($this->decimal_len>0) {
$str .= " And " . $this->decimal . "/" . $this->denominator($this->decimal_len+1) . " Cents";
}
$this->amount_in_words = $str;
}
function denominator($x) {
$temp = "1";
for ($i=1; $i<=$x; $i++) {
$temp .= "0";
}
return $temp;
}
function display() {
echo $this->amount_in_words;
}
function processTen($sub1, $sub2) {
if ($sub1=="0") {
if ($sub2=="0") {
return "";
} else {
return $this->words[$sub2];
}
} elseif ($sub1!="1") {
if ($sub2!="0") {
return $this->words[$sub1."0"] . $this->words[$sub2];
} else {
return $this->words[$sub1 . $sub2];
}
} else {
if ($sub2=="0") {
return $this->words["10"];
} else {
return $this->words[$sub1 . $sub2];
}
}
}
function assign() {
$this->words["1"] = " One"; $this->words["2"] = " Two";
$this->words["3"] = " Three"; $this->words["4"] = " Four";
$this->words["5"] = " Five"; $this->words["6"] = " Six";
$this->words["7"] = " Seven"; $this->words["8"] = " Eight";
$this->words["9"] = " Nine";
$this->words["10"] = " Ten"; $this->words["11"] = " Eleven";
$this->words["12"] = " Twelve"; $this->words["13"] = " Thirten";
$this->words["14"] = " Fourten"; $this->words["15"] = " Fiften";
$this->words["16"] = " Sixten"; $this->words["17"] = " Seventen";
$this->words["18"] = " Eighten"; $this->words["19"] = " Nineten";
$this->words["20"] = " Twenty"; $this->words["30"] = " Thirty";
$this->words["40"] = " Forty"; $this->words["50"] = " Fifty";
$this->words["60"] = " Sixty"; $this->words["70"] = " Seventy";
$this->words["80"] = " Eighty"; $this->words["90"] = " Ninety";
$this->places[0] = ""; $this->places[1] = " Thousand";
$this->places[2] = " Million"; $this->places[3] = " Billion";
$this->places[4] = " Thrillion";
}
}
?>
Problem
You aren't creating an instance of Convert so PHP thinks it's a function.
Solution:
$convert = new Convert($amount);
$convert->display();
On a side note, your Convert method is acting as a constructor function. This is a backwards compatibility function from older versions of PHP. You should follow best-practices by renaming it to __construct now. From the manual:
Warning: Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.
Working example.
Also on a side note - you allow for the currency to be provided as an argument to the constructor method, so you should also allow for the decimal point name as well (Cents) - it's currently hard coded into your Convert method.
I'm working on a project, and I've come across an issue that has me stumped. The code below is a class file and a test page to make sure it's working. It's for somebody else who is programming the site, otherwise I would code the JSON output differently. Basically, the person implementing it just has to pull a bunch of data (like below) from a database, and loop through, instantiating a class object for each result, and plugging each instance into an array, and passing the array to the printJson function, which will print the JSON string. Here is what I have:
Results.php
<?php
class Result
{
public $Category = NULL;
public $Title = NULL;
public $Price = NULL;
public function __construct($category, $title, $price)
{
$this->Category = $category;
$this->Title = $title;
$this->Price = $price;
}
public static function printJson($arrayOfResults)
{
$output = '{"results": [';
foreach ($arrayOfResults as $result)
{
$output += '{"category": "' . $result->Category . '",';
$output += '"title": "' . $result->Title . '",';
$output += '"price": "' . $result->Price . '",';
$output += '},';
}
$output = substr($output, 0, -1);
$output += ']}';
return $output;
}
}
?>
getResults.php
<?php
require_once('Result.php');
$res1 = new Result('food', 'Chicken Fingers', 5.95);
$res2 = new Result('food', 'Hamburger', 5.95);
$res3 = new Result('drink', 'Coke', 1);
$res4 = new Result('drink', 'Coffee', 2);
$res5 = new Result('food', 'Cheeseburger', 6.95);
$x = $_GET['x'];
if ($x == 1)
{
$array = array($res1);
echo Result::printJson($array);
}
if ($x == 2)
{
$array = array($res1, $res2);
echo Result::printJson($array);
}
if ($x == 3)
{
$array = array($res1, $res2, $res3);
echo Result::printJson($array);
}
if ($x == 5)
{
$array = array($res1, $res2, $res3, $res4, $res5);
echo Result::printJson($array);
}
?>
The end result is if I go to getResults.php?x=5, it will return $res1 thru $res5 (again, this is just to test, I would never do something like this in production) formatted as JSON. Right now, I get '0' outputted and I cannot for the life of me figure out why. Could my foreach loop not be written properly? Please, any help you could provide would be awesome!
It's because you're using + for concatenation rather than .:
$output .= '{"category": "' . $result->Category . '",';
$output .= '"title": "' . $result->Title . '",';
$output .= '"price": "' . $result->Price . '",';
$output .= '},';
But you should really not construct the JSON yourself, as it leads to a number of errors making for invalid JSON (trailing commas etc). Use something like this instead:
public static function printJson(array $arrayOfResults)
{
$results['results'] = array_map('get_object_vars', $arrayOfResults);
return json_encode($results);
}