How to format result of array - php

How to format this result of array:
[{"name":"Pendapatan","y":"1464333560100.00"}]
in to this format:
[{name:'Pendapatan',y:1464333560100.00}]
i have try str replace but the result remove all string
[{name:Pendapatan,y:1464333560100.00}]
what should i do?

The only thing that would remotely make sense would be to change "1464333560100.00" to 1464333560100, i.e. change the string to a number. That's a valid change. To do that, you need to make your PHP value a number, not a string:
json_encode(['y' => '1464333560100.00']) → string
json_encode(['y' => 1464333560100.00]) → number
Do note that the result will be 1464333560100, without trailing .00. That's because those two numbers are equivalent; it's irrelevant how many trailing zeros you have, it doesn't change the value as such.
The rest of the formatting change is completely irrelevant. Whether you have single quotes or double quotes or no quotes does not change the data structure and its values at all. If your goal is to produce valid JSON, then the format as is (double quotes everywhere) is in fact necessary.

I got it wrong. You can use this;
json_encode(array('name' => 'Pendapatan', 'y' => 1464333560100.00));
Also you can do the test for json on this site http://jsoneditoronline.org/

Related

How to get NumberFormatter::parse() to only parse actual numeric strings?

I’m trying to parse some strings in some messed-up CSV files (about 100,000 rows per file). Some columns have been squished together in some rows, and I’m trying to get them unsquished back into their proper columns. Part of the logic needed there is to find whether a substring in a given colum is numeric or not.
Non-numeric strings can be anything, including strings that happen to begin with a number; numeric strings are generally written the European way, with dots used for thousand separators and commas for decimals, so without going through a bunch of string replacements, is_numeric() won’t do the trick:
\var_dump(is_numeric('3.527,25')); // bool(FALSE)
I thought – naïvely, it transpires – that the right thing to do would be to use NumberFormatter::parse(), but it seems that function doesn’t actually check whether the string given as a whole is parseable as a numeric string at all – instead it just starts at the beginning and when it reaches a character not allowed in a numeric string, cuts off the rest.
Essentially, what I’m looking for is something that will yield this:
$formatter = new \NumberFormatter('de-DE', \NumberFormatter::DECIMAL);
\var_dump($formatter->parse('3.527,25')); // float(3527.25)
\var_dump($formatter->parse('3thisisnotanumber')); // bool(FALSE)
But all I can get is this:
$formatter = new \NumberFormatter('de-DE', \NumberFormatter::DECIMAL);
\var_dump($formatter->parse('3.527,25')); // float(3527.25)
\var_dump($formatter->parse('3thisisnotanumber')); // float(3)
I figured perhaps the problem was that the LENIENT_PARSE attribute was set to true, but setting it to false ($formatter->setAttribute(\NumberFormatter::LENIENT_PARSE, 0)) has no effect; non-numeric strings still get parsed just fine as long as they begin with a number.
Since there are so many rows and each row may have as many as ten columns that need to be validated, I’m looking at upwards of a million validations per file – for that reason, I would prefer avoiding a preg_match()-based solution, since a million regex match calls would be quite expensive.
Is there some way to tell the NumberFormatter class that you would like it to please not be lenient and only treat the string as parseable if the entire string is numeric?
You can strip all the separators and check if whatever remains is a numeric value.
function customIsNumeric(string $value): bool
{
return is_numeric(str_replace(['.', ','], '', $value));
}
Live test available here.
You can use is_numeric() to check that it is only numbers before parsing. But NumberFormatter does not do what you are looking for here.

In PHP how can i manage strings with exponential numbers

i have a problem with some alphanumeric strings containing the exponential char "E", these are stored into the db in a "character varying" column, so are strings, but when i try to visualize them in the web page i get an "INF" string instead of the original.
For example the following "55E77583" (that for me must be only a code number of an order) becomes "INF" in the webpage.
i've tried to search a solution and i found the sprintf and printf commands, but after some tries with differents %char combinations i'm not able to obtain the original form of the string.
$code = "55E77583";
echo sprintf('%s', $code);
//Gives me "INF"
$code = "55E77583";
printf('%s', $code);
//Gives me always "INF"
I really need to obtain the original form of the string, always, in all the possible alphanumeric combinations. How can i do?
Thank you.
If I understand correctly you want to display the value 55E77583 as string on your webpage. Your provided code above will exactly do that.
So somehow your variable must be converted to double or float before, this is why you receive INF because the number is too large to handle with PHP.
Make sure your variable is actually a string by echoing
echo gettype($code);
This will very likely produce "double". Maybe a type conversion is happening during your select.

Google finance API - trouble fetching currency rates

I'm using Google's currency API to fetch exchange rates and store them in my database, but I ran into some problems. Here's what I'm working with:
http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP
I'm always passing 1USD as the first parameter and exchange that to all the currencies in my database, cast the result variable as a float and store it. Everything works fine until the result from the API is greater than 1000. For example:
http://www.google.com/ig/calculator?hl=en&q=100USD=?PYG
This returns "440 528.634" as the value, and the problem is in the space delimiter. When I cast that to a float it only stores "440". I tried running str_replace() on it before i cast it to a float, but for some reason that doesn't work - I'm guessing it's not a regular whitespace but a special character of some sort. I also tried exploding the variable by a space and returning the merged array fields, but no dice. I'm running out of ideas here so I really hope someone can help me on this :D
Its a non-breaking space character. You can replace it if you refer to it as \xA0:
$result = str_replace("\xA0", "", $result);
Note the double quotes. Use those instead of single quotes as it won't work correctly otherwise.
Its NO BREAK SPACE. You should refer to it as \xA0
$x = str_replace("\xA0", "", $x);
Should work.

json_decode with values containing double quotes

I am trying to use an editable table and have it working except for when the array values passed to the save function contain double quotes. The error occurs at foreach loop
foreach($saveArray as $rowId=>$row) {
It is the values (not keys) which may contain double quotes, the actual error being:
Warning: Invalid argument supplied for foreach()
What is the best way around this, some way to escape them, change them to the &quot code, change the way the loop works?
EDIT:
Sorry, the problem is actually with the json_decode function and double quote values, not returning an array.
Works fine for non double quoted entries
json looks like
{"2":{"component":"8\"", ...
So it is escaped but it's not decoding into an array
See what $saveArray actually is, using
var_dump($saveArray)
It doesn't look like your $saveArray, whatever it is, supports the foreach construct.
If $saveArray comes from json_decode(), it's likely that your JSON string is invalid, and json_decode() just returns NULL.

Why are escaped characters read from database, using PHP, displaying as normal text on output during regular expression replace?

I am trying to store regular expression search and substitution strings in a database. At runtime, I read the database, placing the strings into arrays, and then use the PHP preg_replace() method to update large strings written by users with fixes that my client wants.
Here is a sample string pair I am using:
Search string: /([^\r\n+])(\[url)/i
Substitute string: $1\n\n$2
If I place the string in code like this:
preg_replace("/([^\r\n]+)(\[url)/i", "$1\r\n\r\n$2", ProcessString);
Everything works beautifully. This finds instances of a bbCode tag "[url" that does not have a carriage-return/linefeed combination directly in front of it and places that in front of the "[url" tag.
However, when I run the code as I stated using strings from the database (MySql), the "\r\n\r\n" print literals instead of actually creating carriage-return line feeds. The strings are displayed in a "textarea" tag in HTML.
I have looked at the difference between single and quoted strings and my problem would seem to be this, I am assuming? Thinking that the problem is that the strings coming from the database or inserted into the array I'm looping through are created as single-quoted strings, I tried this:
preg_replace($findKey, "{$replaceValue}", ProcessString);
Where $replaceValue = the string '$1\r\n\r\n$2' (again, I am assuming that reading from the database and/or placing the value into an array (mysql_fetch_assoc($result)) is placing the string value into a single-quoted string and therefore the escaped characters are printing as literals instead of the characters the escaped characters actually represent. However, this did not work.
Here is the code I'm using to insert into the database:
INSERT INTO ISG_TCS_Replacements (FindPhrase, ReplacePhrase, ReplacementGroupID, Description, IsRegEx, IsActive, ProcessGroup, ProcessSequence)
VALUES ("/([^\\r\\n]+)(\\[url)/i","$1\\r\\n\\r\\n$2", 0, "Add a new line after [url] tags that are not on a new line currently.", 1, 1, 0, 1);
The fields are varchar(100).
The issue is that \r\n escapes only work in double quoted strings.
print "\r\n";
Whereas your database usage is likely akin to:
$replaceValue = '\r\n';
print "{$replaceValue}"; // uses the literal character string
You are inserting your replacement string with single quotes into the DB. Otherwise you would get the the actual linebreaks back. Mysql does escape them while inserting, but you always get the original string data back.
Reading from a MySQL TEXT/CHAR column is no different than reading from files really. Check your database with mysqladmin, if you see the literal \r\n then there is your problem.
(A literal '\r\n' btw works in the regex, but not in the replacement string.)
Something else. ([^\r\n+]) is probably meant to be ([^\r\n]+). The quantifier must be outside of the character class.

Categories