I would like to expand a string with one or more values which come from an array.
Desired result:
http://example.com/search/key=["Start", "USA", "Minneapolis"]&shift=false
Array:
array(2) {
[0]=>
string(8) "USA"
[1]=>
string(4) "Minneapolis"
}
PHP Code:
$myArr = ("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start",' .$myArr[0]. ']&shift=false';
Gives me this result: http://example.com/search/key=["Start", "USA"]&shift=false
How can I make it more dynamic so that more than one value can be added? I know I somehow have to use a foreach($myArr as $i){...} and concatenate the values via $string += but because my variable is in the middle of the string I'm kinda stuck with this approach.
Try the following:
$myArr = array("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start", "' . implode('", "', $myArr) . '"]&shift=false';
This will provide the expected output using implode.
Something isn't right here. You are trying to pass array data through a querystring but not in a valid array structure. This means you are either not using it as an array on the next script and you are going to having to chop and hack at it when the data gets there.
I'll make the assumption that you would like to clean up your process...
Declare an array of all of the data that you want to pass through the url's query string, then merge the new key values into that subarray. Finally, use http_build_query() to do ALL of the work of formatting/urlencoding everything then append that generated string after the ? in your url. This is THE clean, stable way to do it.
Code: (Demo)
$myArr = ["USA", "Minneapolis", "monkey=wren[h"];
$data = [
'key' => [
'Start'
],
'shift' => 'false'
];
$data['key'] = array_merge($data['key'], $myArr);
$url = 'http://example.com/search/?' . http_build_query($data);
echo "$url\n---\n";
echo urldecode($url);
Output:
http://example.com/search/?key%5B0%5D=Start&key%5B1%5D=USA&key%5B2%5D=Minneapolis&key%5B3%5D=monkey%3Dwren%5Bh&shift=false
---
http://example.com/search/?key[0]=Start&key[1]=USA&key[2]=Minneapolis&key[3]=monkey=wren[h&shift=false
*the decoded string is just to help you to visualize the output.
Then on your receiving page, you can simply and professionally access the $_GET['key'] and $_GET['shift'] data.
If you have a legitimate reason to use your original malformed syntax, I'd love to hear it. Otherwise, please use my method for the sake of clean, valid web development.
Related
I am struggling a bit to find the correct way of adding a php variable in my json string, with text added just in front of the variable. This is what I have got so far...
$postData = '
{
"message": "Web order '.$order_number.'"
}
';
When I look at the printout there is a line break just after "Web order", but otherwise nothing seems to go wrong... is this the way to do it?
If you want to use json string, then make sure you have properly use your values in your array.
Example:
<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>
Result:
{"message":"Web order 1"}
Here, i am using an array for your data $yourArray and then use json_encode() for json string.
DEMO
Instead of concatenate string, use sprintf()
Dealing directly with Json can become very harmful quickly. Prefer to use array then json_encode instead.
in your case, here is a simple example:
$message = sprintf('Web order %s', $order_number)
$postData = [
'message' => $message
];
$json = json_encode($postData);
I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);
So, i'm trying to access some input fields in a form which I get with
$data = json_encode($app->request->getBody());
It returns something like this after an echo $data:
"groupname=group13&description=description"
But I just can't figure out how to access those parameters, I've tried with
$data[0]
$data['groupname']
$data->groupname
How can I access to this array elements?
[UPDATE]
Tried all of your solutions, none of them worked for me :(
I've finally solved it using this since I only have 2 fields
$groupname = $app->request->post('groupname');
$description = $app->request->post('description');
That is not JSON, it's URL encoded text... Use parse_str() instead.
Friend, in this case if you really need to manage this final query string you can do:
$my_query = "groupname=group13&description=description";
explode elements into a assoc array using parse_str:
parse_str($my_query, $output);
var_dump of $output :
array(2) {
'groupname' =>
string(7) "group13"
'description' =>
string(11) "description"
}
you can remount your query string too using http_build_query:
var_dump(http_build_query($output));
string(41) "groupname=group13&description=description"
I hope this can help you.
Seems like you executed the serialize() method in jQuery
When you do a json_encode(), the output is like {"a":1,"b":2,"c":3,"d":4,"e":5}
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 am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));