I currently have var: $_REQUEST['fb_friend_uid'] which gives me the following output:
Array{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
Im looking to save the data here into a new array, containing only the numbers in a format of; 47483647, 47483647, etc
The objective is to use it in a sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($myNumbers)
Saving it into a new array I figured could be done like so:
foreach ($_REQUEST['fb_friend_uid'] as $uid) {
$uids[] = $uid['id'];
}
$ids = join(',', $uids);
However my issue remains, how to "clean" the first var to contain numbers only.
Suggestions?
I can't give you an exact solution, because I'm not sure if the value returned by $_REQUEST['fb_friend_uid'] is a PHP array printed using json_encode(), or the value is actually a json string.
In either case, where is an example which makes use of both circumstances, so use whichever one makes sense in your scenario:
If PHP Array:
Assumes PHP Array has a format similar to:
array('returned_val' => array('47483647', '47483647', '47483647', '665414807', '263901486', '665414807', '665414807', '665414807'));
<?php
$original_arr = $_REQUEST['fb_friend_uid']['returned_val'];
If JSON String:
Assumes the JSON String has a format similar to:
{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
<?php
$json_arr = json_decode($_REQUEST['fb_friend_uid'], True);
$original_arr = $json_arr['returned_val'];
Then, use this code:
<?php
// Extract only whole number values, omit anything which is not a 0-9 character.
$filtered_arr = array_filter($original_arr, 'ctype_digit');
// Escape values to remove possibility of SQL injection.
$filtered_arr = array_map('mysql_real_escape_string', $filtered_arr);
// Convert the array to a string
$string_arr = "'" . implode("','", $filtered_arr) . "'";
// Perform SQL Query
mysql_query("SELECT * FROM vote WHERE vote_fb_uid IN ($string_arr)");
Just filter the array using is_numeric:
$uids = array_filter($_REQUEST['fb_friend_uid'], 'is_numeric');
To filter for numbers you can use is_numeric( mixed $var ).
But if you need more control (only integers of certain type, length) you can either use REGEX or is_numeric and some ifs.
This looks like a json string, so use http://php.net/json_decode
Maybe you need to remove Array at the beginning (but I don't know if Array is actual in the variable), use http://php.net/substr
$jsonString = substr($_REQUEST['fb_friend_uid'], 5);
$fb_friend_uid = json_decode($jsonString);
$ids = join(',', $fb_friend_uid['returned_val']);
Related
I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.
My session variables are
$_SESSION["listofIds"]=163,164;
$_SESSION["listofVals"]=4,3;
I want to select session values like
$_SESSION["listofIds"][0]=163;
$_SESSION["listofIds"][1]=164;
$_SESSION["listofVals"][0]=4;
$_SESSION["listofVals"][1]=3;
I tried
echo $_SESSION["listofIds"][0];
then it prints '1' i.e. first character. How can I handle this?
Also how can I get 1st element of $_SESSION["listofIds"] and 1st element of $_SESSION["listofVals"] after placing in while loop for mysql query.
Your session variables seem to be strings. Use
$IdsArr = explode(",", $_SESSION["listofIds"]);
echo $IdsArr[0];
With explode splitting the string by "," to an array.
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
now you can access the variables using listofIds[0] or listofIds[1].
First of all you should start by defining from scratch an array while placing values in the $_SESSION array. This is a better way to write code.
Anyway as all the other answers said:
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
will convert your string into an array and you will be able to access each value in different ways. Most commons:
using a foreach loop
getting the index of the item you want to use.
If you want to use the first item in a query you should get its value using the index (array starts from 0) so your value will be $listofids[0]. The same logic will apply to the other $_SESSION value.
Another good practice for programming: when you put an array value in a query string assign it to a variable before:
$id_to_search = $listofids[0];
and then use it into the query:
$sql = "SELECT * FROM your_table WHERE id='$id'";
This will save you a lot of headache with singe and double quotes.
I am running into a problem where the below is not working as I think it should.
// this will not work and $usernames appears empty
$usernames = "\"user1\", \"user2\"";
$query->notContainedIn("username", [$usernames]);
// this does work
$user1 = "user1";
$user2 = "user2";
$query->notContainedIn("username", ["$user1", "$user2"]);
Thanks
According to https://parse.com/docs/php_guide#queries you need to provide an array and $usernames is a string. By using the short-array notation, i.e. the square brackets, you've created an array with precisely one element, namely the string. What you need is an array with two elements corresponding to the two values of interest.
If for some reason your data is only available in this type of formatted string, then you would need to convert it to an array. There are at least two ways you could do this:
<?php
$usernames = explode(",",str_replace("\"","","\"user1\",\"user2\""));
?>
This is less complicated than it might appear. The code replaces the quotes encompassing each value with empty strings. Then it explodes the string in two by indicating that the comma is a delimitor. Although I've never worked with Parse, I would expect that you could replace the second parameter in the query with $usernames now, as follows:
<?php
$query->notContainedIn("username", $usernames);
Don't use the square brackets or you'll be creating a multidimensional array whose first element contains the array $usernames.
Alternative way of converting said string to array:
<?php
$string = "\"user1\",\"user2\"";
$tok = strtok($string, "\",");
$usernames = null;
while ($tok !== false) {
$usernames[] = "$tok";
$tok = strtok("\",");
}
$usernames now contains two values just like in the previous solution I proposed. While this second solution is more involved, note that it uses only one function instead of two, so it might produce faster results. You could try both solutions, benchmark them, and then pick the one you find to have superior performance.
Hope this helps.
I'm trying to build URL query from an Array that looks like that:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
I would like to get query like that:
localhost/get?serial=3804689&serial=3801239&serial=3555689
(you get the idea)
I'm trying to use http_build_query($serials, 'serial', '&'); but it adds the numeric index to the prefix 'serial'.
Any idea how to remove that numeric index?
Well you can't really have the same GET parameter in the string, After all if you try to access that variable server side, what would you use?
$_GET['serial'] - But which serial would it get?
If you really want to get a list of serials, Simply turn the array into a string, save it as an array and there you go. for example :
$serials = "string of serials, delimited by &";
Then you can use the http build query.
Maybe use a foreach:
$get = "localhost/get?serial=" . $serials[0];
unset( $serials[0] );
foreach( $serials AS serial ){
$get .= "&serial=$serial;
}
Just as an FYI, PHP doesn't handle multiple GET variables with the same name natively. You will have to implement something fairly custom. If you are wanting to create a query string with multiple serial numbers, use a delimiter like _ or -.
Ex: soemthing.com/serials.php?serials=09830-20990-91234-12342
To do something like this from an array would be simple
$get_uri = "?serial=" . implode("-", $serials);
You would be able to get the array back from a the string using an explode to
$serials = explode("-", $_GET['serials']);
Yes its quite possible to have such format, you have to build it query string by indices. Like this:
No need to build the query string by hand, use http_build_query() in this case:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$temp = $serials;
unset($serials);
$serials['serial'] = $temp;
$query_string = http_build_query($serials);
echo urldecode($query_string);
// serial[0]=3804689&serial[1]=3801239&serial[2]=3555689&serial[3]=3804687&serial[4]=1404689&serial[5]=6804689&serial[6]=8844689&serial[7]=4104689&serial[8]=2704689&serial[9]=4604689
And then finally, if you need to process it somewhere, just access it thru $_GET['serial'];
$serials = $_GET['serial']; // this will now hold an array of serials
You can also try this
$get = "localhost/get?serial=";
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$list = implode("&serial=",$serials);
echo $get.$list;
Having the same GET parameter will not work this way. You will need to use an array in the get parameter:
localhost/get?serial[]=3804689&serial[]=3801239&serial[]=3555689
IF you just print $_GET through this URL, you will receive
Array ( [serial] => Array ( [0] => 380468 [1] => 3801239 [2]=> 3555689) )
Then you can do this to build your query string
$query_str = 'serial[]='.implode('&serials[]=',$serials);
You can try this version.
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$get = implode('&serials[]=',$serials);
echo 'test';
var_dump($_GET['serials']);
Result
I'm trying to implode variables, but it's not working correctly:
$models = array("$model0, $model1");
$modelfinal = implode("," , $models);
$modelfinal only returns , ,
I'm guessing I'm way off...anybody?
The following statement creates an array with exactly one string in it, which is comprised of the values of two (apparently) undefined variables separated with a comma:
$models = array("$model0, $model1");
The end result is the same as if you had done this:
$models = array(", ");
Now you're imploding it using a comma as the separator, which doesn't do anything since there's only one element in the array (a string with a comma and a space).
Assuming $model0 and $model1 are defined (which is a problem you'll need to look into first), you can get your desired result either by:
directly using $modelfinal = "$model0, $model1",
or by using $models = array($model0, $model1); followed by the implode.
here is your problem "$model0, $model1" change it to this code
$models = array($model0,$model1);