I ran into an issue with a data feed I need to import where for some reason the feed producer has decided to provide data that should clearly be either INT or FLOAT as strings-- like this:
$CASES_SOLD = "THREE";
$CASES_STOCKED = "FOUR";
Is there a way in PHP to interpret the text string as the actual integer?
EDIT: I should be more clear-- I need to have the $cases_sold etc. as an integer-- so I can then manipulate them as digits, store in database as INT, etc.
Use an associative array, for example:
$map = array("ONE" => 1, "TWO" => 2, "THREE" => 3, "FOUR" => 4);
$CASES_SOLD = $map["THREE"]; // 3
If you are only interested by "converting" one to nine, you may use the following code:
$convert = array('one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
);
echo $convert[strtolower($CASES_SOLD)]; // will display 3
If you only need the base 10 numerals, just make a map
$numberMap = array(
'ONE' => 1
, 'TWO' => 2
, 'THREE' => 3
// etc..
);
$number = $numberMap[$CASES_SOLD];
// $number == 3'
If you need something more complex, like interpreting Four Thousand Two Hundred Fifty Eight into 4258 then you'll need to roll up your sleeves and look at this related question.
Impress your fellow programmers by handling this in a totally obtuse way:
<?php
$text = 'four';
if(ereg("[[.$text.]]", "0123456789", $m)) {
$value = (int) $m[0];
echo $value;
}
?>
You need a list of numbers in english and then replace to string, but, you should play with 'thousand' and 'million' clause where must check if after string 'thousend-three' and remove integer from string.
You should play with this function and try change if-else and add some functionality for good conversion:
I'm writing now a simple code for basic, but you know others what should change, play!
Look at million, thousand and string AND, it should be change if no in string like '1345'. Than replace with str_replace each of them separaterly and join them to integer.
function conv($string)
{
$conv = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
'FOUR' => 4,
'FIVE' => 5,
'SIX' => 6,
'SEVEN' => 7,
'EIGHT' => 8,
'NINE' => 9,
'TEN' => 10,
'ELEVEN' => 11,
'TWELVE' => 12,
'THIRTEEN' => 13,
'FOURTEEN' => 14,
'FIFTEEN' => 15,
'SIXTEEN' => 16,
'SEVENTEEN' => 17,
'EIGHTEEN' => 18,
'NINETEEN' => 19,
'TWENTY' => 20,
'THIRTY' => 30,
'FORTY' => 40,
'FIFTY' => 50,
'SIXTY' => 60,
'SEVENTY' => 70,
'EIGTHY' => 80,
'NINETY' => 90,
'HUNDRED' => 00,
'AND' => '',
'THOUSAND' => 000
'MILLION' => 000000,
);
if (stristr('-', $string))
{
$val = explode('-', $string);
#hardcode some programming logic for checkers if thousands, should if trim zero or not, check if another values
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
else
{
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
}
Basically what you want is to write a parser for the formal grammar that represents written numbers (up to some finite upper bound). Depending on how high you need to go, the parser could be as trivial as
$numbers = ('zero', 'one', 'two', 'three');
$input = 'TWO';
$result = array_search(strtolower($input), $numbers);
...or as involved as a full-blown parser generated by a tool as ANTLR. Since you probably only need to process relatively small numbers, the most practical solution might be to manually hand-code a small parser. You can take a look here for the ready-made grammar and implement it in PHP.
This is similar to Converting words to numbers in PHP
PHP doesn't have built in conversion functionality. You'd have to build your own logic based on switch statements or otherwise.
Or use an existing library like:
http://www.phpclasses.org/package/7082-PHP-Convert-a-string-of-English-words-to-numbers.html
Related
This question already has answers here:
PHP - Check if two arrays are equal
(19 answers)
Check if two arrays have the same values (regardless of value order) [duplicate]
(13 answers)
How to check if PHP associative arrays are equal, ignoring key ordering?
(1 answer)
Closed 4 years ago.
I'm trying to match 2 arrays that look like below.
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
My problem is, I need the array keys of both arrays to be the same value and same count.
Which means:
// passes - both arrays have the same key values and same counts of each key
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
// fails - $public does not have 'blue' => 1
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('red' => 2, 'green' => 3, 'purple' => 4);
// should fail - $public has 2 'blue' => 1
$system = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$public = array('blue' => 1, 'blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
I've tried using array_diff_keys, array_diff and other php functions, but none can catch extra keys with the same value (i.e. if 'blue' => 1, is repeated it still passes)
What's a good way to solve this?
When you write two values with same key in PHP, the second one will overwrite the value from the first (and this is not an error). Below is what I did on the PHP interactive CLI (run it with php -a):
php > $x = ["x" => 1, "x" => 2, "y" => 2];
php > var_dump($x);
array(2) {
["x"]=>
int(2)
["y"]=>
int(2)
}
So array_diff seems to be working correctly. You are just expecting PHP to behave in a different way than it actually does!
I need some help with generation of combinations, specifically in the store they're the variants of each product, e.g size and colour.
Let's say we have 3 customizable properties of the product:
Colour, Size, and Type.
For this specific product, the following are available of each property:
Color: [red, green], Size: [10, 11, 15], Type: [person]
Now according to the above data, I need to generate 6 combinations, however if we added another type it would increase even more.
I have been drawing on my board for 2 hours now trying to come up with a sane algorithm for this, something that's fast and can deal with thousands of combinations in a matter of seconds.
Take this example:
$options = ['Color' => ['Red', 'Green'], 'Size' => ['10', '11', '15'], 'Type' => ['person']];
$combinations = generateCombinations($options);
genereateCombinations would then need to generate the following output:
[
['Color' => 'Red', 'Size' => '10', 'Type' => 'person'],
['Color' => 'Red', 'Size' => '11', 'Type' => 'person'],
['Color' => 'Red', 'Size' => '15', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '10', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '11', 'Type' => 'person'],
['Color' => 'Green', 'Size' => '15', 'Type' => 'person']
];
What algorithm could do this efficiently and with unlimited input "titles"? (of course I'll enforce a limit earlier, but the algorithm should be able to do unlimited granted all the resources in the world)
Extending what I mean:
This function also needs to be able to take for example an array with 100 property rows, not just 3, it needs to be able to do this dynamically no matter the number of input rows.
Three foreach loops are enough to generate all combinations, no matter how many entries are in $options:
function generateCombinations(array $options)
{
// Start with one combination of length zero
$all = array(array());
// On each iteration append all possible values of the new key
// to all items in $all; generate this way all the combinations
// one item longer than before
foreach ($options as $key => $values) {
// Move all combinations of length N from $all to $current
$current = $all;
// Start with an empty list of combinations of length N+1
$all = array();
// Combine each combination of length N
// with all possible values for the (N+1)th key
foreach ($current as $one) {
foreach ($values as $val) {
// Put each new combination in $all (length N+1)
$all[] = array_merge($one, array($key => $val));
}
}
}
return $all;
}
$options = [
'Color' => ['Red', 'Green'],
'Size' => ['10', '11', '15'],
'Type' => ['person'],
'Answer' => ['Yes', 'No'],
];
$combinations = generateCombinations($options);
echo(count($combinations));
# 12
It can probably be slightly improved but, all in all, if you don't know in advance the length of $options it does a lot of duplicate iterations. If you know in advance the number of items in $options (let's say it is N) then N nested loops are the fast way to do it.
I have this array in PHP:
$weekdays = array(
"mandag" => 1,
"tirsdag" => 2,
"onsdag" => 3,
"torsdag" => 4,
"fredag" => 5,
"lørdag" => 6,
"søndag" => 7);
The function gets the day with random formats like all uppercase or one letter uppercase, I'm doing an strtolower from the variable and then comparing it with the array.
The problem comes here, when I do strtolower on the var with a special character like this one ø from søndag and lørdag, it doesn't recognize the string. How can I change the string to strtolower without modifying the special character?
Try mb_strtolower
$weekdays = array("Mandag" => 1, "Tirsdag" => 2, "Onsdag" => 3, "Torsdag" => 4, "Fredag" => 5, "Lørdag" => 6, "Søndag" => 7);
$weekdays = array_combine(
array_map('mb_strtolower', array_keys($weekdays)),
$weekdays
);
var_dump($weekdays);
...or if you want to check a specific item in the array you can simply run mb_strtolower($item, 'UTF-8') on it.
$happyDay = "SøndAg";
echo $happyDay . ' -> ' . mb_strtolower($happyDay, 'UTF-8');
It seems that arrays sorted before comparing each other inside array_diff_uassoc.
What is the benefit of this approach?
Test script
function compare($a, $b)
{
echo("$a : $b\n");
return strcmp($a, $b);
}
$a = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$b = array('v' => 1, 'w' => 2, 'x' => 3, 'y' => 4, 'z' => 5);
var_dump(array_diff_uassoc($a, $b, 'compare'));
$a = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$b = array('d' => 1, 'e' => 2, 'f' => 3, 'g' => 4, 'h' => 5);
var_dump(array_diff_uassoc($a, $b, 'compare'));
$a = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$b = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
var_dump(array_diff_uassoc($a, $b, 'compare'));
$a = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$b = array('e' => 5, 'd' => 4, 'c' => 3, 'b' => 2, 'a' => 1);
var_dump(array_diff_uassoc($a, $b, 'compare'));
http://3v4l.org/DKgms#v526
P.S. it seems that sorting algorithm changed in php7.
Sorting algorithm didn't change in PHP 7. Elements are just passed in another order to the sorting algorithm for some performance improvements.
Well, benefit could be an eventual faster execution. You really hit worst case when both arrays have completely other keys.
Worst case complexity is twice sorting the arrays and then comparisons of each key of the two arrays. O(n*m + n * log(n) + m * log(m))
Best case is twice sorting and then just as many comparisons as there are elements in the smaller array. O(min(m, n) + n * log(n) + m * log(m))
In case of a match, you wouldn't have to compare against the full array again, but only from the key after the match on.
But in current implementation, the sorting is just redundant. Implementation in php-src needs some improvement I think. There's no outright bug, but implementation is just bad. If you understand some C: http://lxr.php.net/xref/PHP_TRUNK/ext/standard/array.c#php_array_diff
(Note that that function is called via php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); from array_diff_uassoc)
Theory
Sorting allows for a few shortcuts to be made; for instance:
A | B
-------+------
1,2,3 | 4,5,6
Each element of A will only be compared against B[0], because the other elements are known to be at least as big.
Another example:
A | B
-------+-------
4,5,6 | 1,2,6
In this case, the A[0] is compared against all elements of B, but A[1] and A[2] are compared against B[2] only.
If any element of A is bigger than all elements in B you will get the worst performance.
Practice
While the above works well for the standard array_diff() or array_udiff(), once a key comparison function is used it will resort to O(n * m) performance because of this change while trying to fix this bug.
The aforementioned bug describes how custom key comparison functions can cause unexpected results when used with arrays that have mixed keys (i.e. numeric and string key values). I personally feel that this should've been addressed via the documentation, because you would get equally strange results with ksort().
Maybe this isn't possible, I've never seen it myself, but thought I'd ask. If this is my array,
$myarr = array(
'red' => 7,
'green' => 7,
'blue' => 18,
'cyan' => 14,
'pink' => 18
'brown' => 18
);
is there a way while initializing the array to set similar values at once? like
'red' && 'green' =>7,
'blue' && 'pink' && 'brown' => 18,
'cyan' =>14
of course I'm not expecting this syntax to work but is there something that gets me the same idea?
PHP Manual does not provide description of any way to do that. BTW, you may initialize values in the following way:
$myarr['red'] = $myarr['green'] = 7;
$myarr['blue'] = $myarr['pink'] = $myarr['brown'] = 18;
$myarr['cyan'] = 14;
It isn't possible and, honestly, I fail to see a situation it could be useful if the repeated values are in the same array.
Would you like to provide an example, in order for me to get it?
A fun aside:
$bibi = array (
'foo' == 'bar' => 2,
);
$bubu = array (
'foo' && 'bar' => 2,
);
Both this syntaxes actually evaluate the expressions on the left. As in, in 2 is assigned to $bibi[0] and $bubu[1].