I tried using lpush
$list = "flavors";
$array = array($_GET["mainid"], $_GET["flavor1"], $_GET["flavor2"], $_GET["flavor3"]);
$redis = new Predis\Client();
$redis->lpush($list,implode("", $array));
echo $redis->lrange(0, -1);
I have tried using hset
$redis->hset("flavors", $_GET["mainid"], $_GET["mainid"]);
$redis->hset("flavors", $_GET['mainid'] . "flavor1", $_GET["flavor1"]);
$redis->hset("flavors", $_GET['mainid'] . "flavor2", $_GET["flavor2"]);
$redis->hset("flavors", $_GET['mainid'] . "flavor3", $_GET["flavor3"]);
echo $redis->hgetall($_GET['mainid']);
But I can't get that to work because I get this error: http://pastie.org/8401717
How could I fix that? I think it is something about being given an array when it expects a string, but I have implode in there, so why else isn't it working? If it can't work at all, what other Redis data type could I use?
You got that error when using lpush because the flavors key is already stored with a different Redis data type. So you should delete that key before you try again.
You also used lpush in wrong way. You should try this:
foreach ($array as $value) {
$redis->lpush($list, $value);
}
Or if your redis api support multi params:
call_user_func_array(array($redis, 'lpush'), array_merge($list, $array));
If you want to store flavors by mainid, you may want to store it with multi keys and use lpush:
$list = "flavor:{$_GET['mainid']}";
$redis->lpush($list, $_GET["flavor1"]);
$redis->lpush($list, $_GET["flavor2"]);
$redis->lpush($list, $_GET["flavor3"]);
Another way is to store in a single hash and using json_encode (don't use implode):
$data = json_encode(array($_GET["flavor1"], $_GET["flavor2"], $_GET["flavor3"]));
$redis->hset('flavors', $_GET["mainid"], $data);
Related
I am using a plugin in my wordpress that stores my data in a specific way. I have a problem on how to extract that data into an array using php. The data currently saved in database is in this kind of format which i have never seen before. I want to get the name, price and the referral amount from this data.
I have tried using php foreach looping to extract data but it wont recognize the foreach function.
a:2:{i:0;a:4:s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}
I wanted the array to store the data in this kind of way:
{
name:'Tower',
price:500,
referral_amount:20,
}
Does anyone knew how to extract this kind of data using php?
$data = 'a:2:{i:0;a:4:{s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:{s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}';
$data = preg_replace_callback('!s:(\d+):"(.*?)";!',
function ($match) {
return 's:'.strlen($match[2]).':"'.$match[2].'";';
},
$data);
$data_array = unserialize($data);
$final_data = json_encode($data_array);
echo $final_data;
How do I separate my array strings delimiter (|) using the implode function of PHP something like the below String
|Java||PHP||Bootstrap||HTML||CSS|
Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
What I have tried:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
array_push($array_service_offer, $selectedOption);
}
//$service_offer = implode(',',$array_service_offer);
$service_offer = '|' . implode('||', $array_service_offer) . '|';
} else {
$service_offer = "";
}
First of all, according to #Qirel comment, I would also recommend to use $array_service_offer[] = $selectedOption; instead of array_push($array_service_offer, $selectedOption);
now for separation, there are several solutions.
One solution is that:
1- to remove first and last | character (it is like trimming)
2- to explode the trimmed string using || delimiter
for that you may use the following code:
$service_offer_trimmed = preg_replace("~(^\|)|(\|$)~", "", $service_offer);
$service_offer_array = explode('||', $service_offer_trimmed);
The other solution is to use straight forward preg_replace function to separate the string. the command follows:
$service_offer_array = preg_split("~(^\|)|(\|\|)|(\|$)~", $service_offer, 0, PREG_SPLIT_NO_EMPTY);
And one more professional solution is that to store your data in database in JSON format rather than delimited code and then when you need to search in your database you may use MySql JSON_CONTAINS function rather than LIKE command.
I have not personally made a performance check on both two solutions but if it not a big database, then it is not a big concern as well.
Therefore, you initial code to get the data and store it into the database will be:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
$array_service_offer[] = $selectedOption;
}
}
// $json_service_offer will be saved to the database
$json_service_offer = json_encode($array_service_offer);
the manual on how to use JSON_CONTAINS is in the following link:
12.17.3 Functions That Search JSON Values
My Web App uses Laravel & MySQL but for my tests I am using SQLite in memory.
This is my code that I use in my Controller:
$opportunities = DB::table('opportunities')
->whereRaw('JSON_CONTAINS(businesses, \'"' . $business . '"\')')
->get();
When testing this throws an exception because of how SQLite doesn't have a JSON_CONTAINS function. How can I get around this so that my tests pass and I don't have to make any massive changes to the structure? Does SQLite have a function for this or something along these lines?
Thanks
You could emulate JSON_CONTAINS during testing using sqlite_create_function e.g.
function json_contains($json, $val) {
$array = json_decode($json, true);
// trim double quotes from around the value to match MySQL behaviour
$val = trim($val, '"');
// this will work for a single dimension JSON value, if more dimensions
// something more sophisticated will be required
// that is left as an exercise for the reader
return in_array($val, $array);
}
sqlite_create_function(<your db handle>, 'JSON_CONTAINS', 'json_contains');
You may also want to emulate the optional third parameter of JSON_CONTAINS e.g.
function json_contains($json, $val, $path = null) {
$array = json_decode($json, true);
// trim double quotes from around the value to match MySQL behaviour
$val = trim($val, '"');
// this will work for a single dimension JSON value, if more dimensions
// something more sophisticated will be required
// that is left as an exercise for the reader
if ($path)
return $array[$path] == $val;
else
return in_array($val, $array);
}
A bit more explanation for the accepted answer:
/**
* Call this method in your test.
* #PHP 7.4+
*/
private function setupSqlite(): void
{
DB::connection()->getPdo()->sqliteCreateFunction('JSON_CONTAINS', function ($json, $val, $path = null) {
$array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// trim double quotes from around the value to match MySQL behaviour
$val = trim($val, '"');
// this will work for a single dimension JSON value, if more dimensions
// something more sophisticated will be required
// that is left as an exercise for the reader
if ($path) {
return $array[$path] == $val;
}
return in_array($val, $array, true);
});
Then you can use this query, that works for both mysql/mariadb and sqlite:
$result = Product::whereRaw('JSON_CONTAINS(tags, \'"' . $tag . '"\')')->get();
In above example I was searching json column with simple array:
$column = ["example", "test", "simple"];
I gave up on running my test suite on SQLite because there are just too many differences between the implementations. The first issue was it's lack of support for enums, but when even simple things like ALTER statements were causing problems I changed to MySQL for testing too.
What I do now is specify the name of my testing db in phpunit.xml.
<phpunit>
<php>
<env name="DB_DATABASE" value="mydb_testing"/>
</php>
</phpunit>
The down side of this is being required to create two databases to develop the app, but I need to be sure that the migrations will work on production, which uses MySQL and testing on SQLite doesn't prove that.
re: Home Site = http://mobiledetect.net/
re: this script = Mobile_Detect.php
Download script here: https://github.com/serbanghita/Mobile-Detect
This script functions perfectly detecting the different parameters of a user's device.
However, this is how I am currently detecting these parameters:
// each part of the IF statement is hard-coded = not the way to do this
if($detect->isiOS()){
$usingOS = 'iOS';
}
if($detect->isAndroidOS()){
$usingOS = 'Android';
}
echo 'Your OS is: '.$usingOS;
My goal is to use a FOREACH to iterate thru the various arrays in this script to determine a user's device's parameters. I would need to have the "($detect->isXXXXOS())" be dynamic... (which, would be based upon the KEY). The results would display the KEY. But the detection would be based upon the VALUE.
Also, since my web page uses a REQUIRE to access this script... in the Mobile_Script.php script, the arrays are "protected." I think this is also causing me problems (but I don't know for sure).
Any help is appreciated.
In foreach loop you can call dynamic method look like this :
$array = array('Android','Windows','Linux','Mac');
foreach( $array as $value) {
$method = "is{$value}OS";
if($detect->$method()) {
$os = $value;
echo "Your OS is : {$os}";
}
}
Please rearrange your code what you want. I give you an example.
you can try to use somethin like this:
$OSList = $detect->getOperatingSystems();// will give array of operating system name => match params
foreach($OSList as $os_name=>$os_params/*unused*/)
{
$method = 'is'.$os_name;
if($detect->$method())
{
$usingOS = $os_name;
}
}
I am trying to use jQuery Autocomplete Plugin in my PHP web application.
I have a JSON file on the server that has the data for the search. It looks like this:
{
"_E161": {
"keggId":"rn:R05223",
"abbrev":"ADOCBLS",
"name":"Adenosylcobalamin 5'-phosphate synthase",
"equation":"agdpcbi[c] + rdmbzi[c] -> h[c] + adocbl[c] + gmp[c] ",
},
"_E163": {
....
}
}
I would like to go through this JSON file (has 3500 entries) with PHP script that gets search term from the jQuery autocomplete plugin. Then return the entries that contain search term back to client side to populate autocomplete.
What would be a better way to implement this? My first guess is to loop through the JSON file and use strpos() But I suspect that might be slow?
You can make use on preg_grep (Return array entries that match the pattern),
// sanitize, and perform some processing to ensure is a valid regex pattern
$pattern = ...;
$json = json_decode( ... );
$arr = array();
foreach ($json as $key=>$arr)
{
$arr[$key] = $arr['name'];
}
$matches = preg_grep("/$pattern/i", $arr);
// $matches will hold the matches
// and you refer back to the $json using associate key