PHP Build url query from array - php

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

Related

how to do replace and explode for array input in laravel

I am beginner to laravel. I am trying to access array input from my API request.
For postman, I have array as key called file_name_list and its value like ["m_profile.png","aa_image.jpg","new_pan.jpg"]. I want to access that array in my controller. That values should go into 3 seperate variables like
$profile = m_profile.png
$aadhar = aa_image.jpg
$pan = new_pan.jpg
For that I am trying to use replace and explode functions in controller.
$filenamelist1 = Str::replaceArray(array(' ','"', '[',']'),[""], $request->file_name_list);
$filename_str = explode(",",$filenamelist1);
After this I want to store values from explode array to 3 variables as mentioned above using for loop
But I am facing problems like in Str::replaceArray 2 parameter should be array and for explode 2 parameter should be string.
How should I use replace and explode to get required result? please guide. Thanks in advance.
You can use list method like below:
list( $profile , $adhar, $pan) = $request->file_name_list;
Check the Docs
If Your array size fixed then you assign that by using list
list( $profile,$adhar,$pan) = $request->file_name_list;
<?php
$value = '["m_profile.png","aa_image.jpg","new_pan.jpg"]';
$value = str_replace("[","",$value); // clean [
$value = str_replace("]","",$value); // clean ]
$arrayValues = explode('","',$value); // explode with ","
print_r($arrayValues);
output
Array (
[0] => "m_profile.png
[1] => aa_image.jpg
[2] => new_pan.jpg"
)
Replace " when you access the values

PHP get user id in url 4

I want to get the id from my url like below
http://localhost/cpanel-ar/stage_one/reports.php?temp=temp_21day
How can GET only the "temp"?
I assume that you mean this:
$getVars = array_keys($_GET);
print_r($getVars);
This will return an array with your get parameters.
for example:
http:example.com?getparameter=getvalue
returns:
Array ( [0] => getparameter )
why you dont try to use substr function?
$data = $_GET['temp'];
echo substr($data,0,4);
its will only catch temp
i dont know if i understood but you can use predefined variables using:
$temp = $_GET['temp'];
but if you are using a framework maybe they already is handle that.
if you want the 'temp' name and you know witch parameters are passed to URL you can use
array_keys($_GET)[i]
Where i i the index of parameter

how to save numbers only from an array into a new array

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']);

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

PHP: problem inserting array inside an array

I have a script that is using the google charts API and the gChart wrapper.
I have an array that when dumped looks like this:
$values = implode(',', array_values($backup));
var_dump($values);
string(12) "8526,567,833"
I want to use the array like this:
$piChart = new gPieChart();
$piChart->addDataSet(array($values));
I would have thought this would have looked like this:
$piChart->addDataSet(array(8526,567,833));
Howerver when I run the code it creates a chart with only the first value.
Now when I hardcode the values in instead I get each value in the chart.
Does anyone know why it's acting this way?
Jonesy
I think
$piChart->addDataSet(array_values($backup));
// or just: $piChart->addDataSet($backup); depends on $backup
should do it.
$values only contains a string. So if you do array($values), you create an array with one element:
$values = "8526,567,833";
print_r(array($values));
gives
Array
(
[0] => 8526,567,833
)
array(8526,567,833) would be the same as array_values($backup) or maybe even just $backup, that depends on the $backup array.
Looks like you want to use $backup instead of $values as $values is the imploded string... and since 8526,567,833 isn't a valid number, it parses 8526 and leaves the rest alone.

Categories