I have these following code. could anyone please explain it to me about these code, I did not get all of them.
here is the code
$query = $_SERVER['QUERY_STRING'];
$query = explode('&', $_SERVER['QUERY_STRING']);enter code here
$params = array();
foreach ($query as $param) {
list($name, $value) = explode('=', $param, 2);
$params[urldecode($name)][] = urldecode($value);
}
//echo jsonEncode($params);
$categories = implode(", ", $params['categories']);
$types = implode(", ", $params['type']);
I am confused about these two variables "$param" & "$params"
If a page is accessed via any query string, $_SERVER['QUERY_STRING'] fetches that query string.
for example, if you call url in your browser like this
http://example.com/index.php?name=msk&job=developer
then $_SERVER['QUERY_STRING'] contain following data
"name=msk&job=developer"
and explode() used to convert string to array where delimeter is &
$query = explode('&', $_SERVER['QUERY_STRING']);
now $query contain array with following data
Array
(
[0] => "name=msk"
[1] => job=developer"
)
.
$params = array(); //created to hold $_SERVER['QUERY_STRING'] array of strings
foreach ($query as $param) {
list($name, $value) = explode('=', $param, 2);
//above line try to convert "name=msk" into array like this ["name"] => array([0] = msk)
//list() function is used to assign values to a list of variables in one operation.
$params[urldecode($name)][] = urldecode($value);
}
$params contain following array data
(
["name] => Array
(
[0] => msk
)
[job] => Array
(
[0] => developer"
)
)
echo json_encode($params);
json_encode() used for converting php array to JSON
{"\"name":["msk"],"job":["developer\""]}
and come to your doubt
$param is just a loop iterator
$params is array used for holding $_SERVER['QUERY_STRING'] data
Related
I have a table on the frontend, where the user can choose what types of columns he wants.
After submitting the form I get the array with selected columns.
For instance the user select following columns:
$columns = ["campaign_start_time", "campiagn_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"]
Now I have to make the request to the facebook api, but facebook api only request query in form:
$query = "campaign{start_time, end_time, id, budget}, adset{name}, ad{name}"
Here is my question, what is the best way to convert $columns to $query in PHP language?
If you can construct your submitted data to be in this form:
Array
(
[campaign] => Array
(
[0] => start_time
[1] => end_time
[2] => id
[3] => budget
)
[adset] => Array
(
[0] => name
)
[ad] => Array
(
[0] => name
)
)
Maybe using inputs or other constructs such as:
name="campaign[]" value="start_time"
name="campaign[]" value="end_time"
Then looping and building the query with the keys and values will do it:
foreach($columns as $key => $val) {
$query[] = $key . '{' . implode(',', $val) . '}';
}
$query = implode(',', $query);
Otherwise you'll need to parse it to get what you need first, then execute the loop above using $result instead:
foreach($columns as $val) {
preg_match('/^([^_]+)_(.*)/', $val, $match);
$result[$match[1]][] = $match[2];
}
This solution splits apart the values based on underscores and then joins them back together as nested values based on the category/key. Note that this doesn't check for items that don't have a "prefix".
<?php
$columns = ["campaign_start_time", "campaign_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"];
$criteria = [];
foreach( $columns as $column ){
$pieces = explode('_',$column);
$category = array_shift($pieces);
if( !isset($criteria[$category]) ){
$criteria[$category] = [];
}
$criteria[$category][] = implode('_', $pieces);
}
$queryPieces = [];
foreach($criteria as $category => $values){
$queryPieces[] = $category.'{'.implode(', ', $values).'}';
}
$query = implode(', ', $queryPieces);
I have the following array of countries ($countryIso = array("US","BR","CL");) and my idea is to create a new array to display the following schema:
('US', 200)
I tried to create the following structure:
$countryIso = array("US","BR","CL");
foreach ($countryIso as $isocode) {
$productcalc[] = "'" . strtoupper($isocode) . "'" . ',' . number_format($this->product->calculate($product = $product, $countryIso = $isocode), 0, '.', ',');
}
Despite I can create a look alike format, I realized that the array is not well formed. When I checked the output displays the following:
Array ( [0] => 'US',200
being the key is [0] and not US.
Any idea of how can I create a key => value result with
Array ( [US] => 200
using the foreach structure in my code? I tried with variants like array_combine to combine countryIso array with productcalc array but with no success
You can keep your iso array and simply just combine the arrays:
<?php
$iso = ['US', 'BR', 'CL'];
$values = [200, 300, 400]; # obviously populate this with your actual values
$newArray = array_combine($iso, $values); # array_combine($keys, $values)
echo '<pre>'. print_r($newArray, 1) .'</pre>';
Edit: Further thoughts if Values are got via iso value
<?php
$iso = ['US', 'BR', 'CL'];
$newArray = [];
foreach ($iso as $val)
{
$newArray[$val] = getValueFromIso($val); # not a real function - just an example
}
Just define the array with the correct values.
$countryIso =[
"US" => 200,
"BR" => 300,
"CL" => 400,
];
If the values need to be calculated use:
$countryIso = array("US","BR","CL");
foreach ($countryIso as $isocode) {
$productcalc[strtoupper($isocode)] = number_format($this->product->calculate($product = $product, $countryIso = $isocode), 0, '.', ',');
}
Now $productcalc is the array you need.
I has a string like as brachA-branchB-branchC. I am trying to make it as nested array as follows
[
'name'=>'brachA',
'sub'=> [
'name'=>'brachB',
'sub'=>[
'name'=>'brachC'
]
]
]
I tried as follows (https://3v4l.org/A781D)
<?php
$nested_array = array();
$temp = &$nested_array;
$item = 'brachA-branchB-branchC';
foreach (explode('-', $item) as $key => $value) {
$temp = &$temp[$value];
}
print_r($nested_array);
Output I am getting as follows
Array
(
[brachA] => Array
(
[branchB] => Array
(
[branchC] =>
)
)
)
Any idea, how to achieve this ?
It can probably be done using a foreach loop over the reversed array returned by explode() but it is much easier to use a recursive function.
function makeArray(array $pieces)
{
$first = array_shift($pieces);
$array = array('name' => $first);
if (count($pieces)) {
$array['sub'] = makeArray($pieces);
}
return $array;
}
$item = 'brachA-branchB-branchC';
print_r(makeArray(explode('-', $item)));
The makeArray() function receives an array with the string pieces. It puts the first item under the 'name' key of a new array and invokes itself with the rest of the array to generate the array to put under the 'sub' key. It doesn't put anything for the 'sub' key if there is no rest (on the last call, $pieces is array('brachC').
This is the initial string:-
NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n
This is my solution although the "=" in the end of the string does not appear in the array
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);
//create new array to push data in the foreach
$newArray = array();
foreach($env as $val){
// Split string on every "=" and write into array
$result = preg_split ('/=/', $val);
if($result[0] && $result[1])
{
$newArray[$result[0]] = $result[1];
}
}
print_r($newArray);
This is the result I get:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )
But I need :
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )
You can use the limit parameter of preg_split to make it only split the string once
http://php.net/manual/en/function.preg-split.php
you should change
$result = preg_split ('/=/', $val);
to
$result = preg_split ('/=/', $val, 2);
Hope this helps
$string = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate = [ 'NAME=' => '"NAME":"' ,
'LOCATION=' => '","LOCATION":"',
'SECRET=' => '","SECRET":"' ,
'\n' => '' ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array = json_decode($jsonified, true);
This is based on 1) translation using strtr(), preparing an array in json format and then using a json_decode which blows it up nicely into an array...
Same result, other approach...
You can also use parse_str to parse URL syntax-like strings to name-value pairs.
Based on your example:
$newArray = [];
$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);
array_walk(
$env,
function ($i) use (&$newArray) {
if (!$i) { return; }
$tmp = [];
parse_str($i, $tmp);
$newArray[] = $tmp;
}
);
var_dump($newArray);
Of course, you need to put some sanity check in the function since it can insert some strange stuff in the array like values with empty string keys, and whatnot.
I know what you're thinking. "I can answer this question so quick! It's the parse_str function!" But I've got a little twist for you.
You see, PHP converts the names of all query data into valid PHP variable names. What? Even when they're not being stored as variables? Where is that documented? It isn't.
$payload = 'data.name=value&data.other=value2';
parse_str($payload, $values);
var_export($values);
// Outputs: array('data_name' => 'value', 'data_other' => 'value2')
// Expected: array('data.name' => 'value', 'data.other' => 'value2')
How can I parse a query string without this happening?
You can avoid PHP's renaming of parameter names by parsing the query string yourself. Split the string on & and = characters, and then urldecode() each part:
<?php
$payload = 'data.name=value&data.other=value2';
$values = array();
$nv_strings = explode ('&', $payload);
foreach ($nv_strings as $s) {
$nv = explode ('=', $s, 2);
$name = urldecode ($nv[0]);
$value = (isset ($nv[1]) ? urldecode ($nv[1]) : null);
$values[$name] = $value;
}
print_r ($values);
// Array
// (
// [data.name] => value
// [data.other] => value2
// )
If your query string contains duplicate keys, the above code will overwrite the previous keys. This also can be solved:
<?php
$payload = 'key=val1&key=val2&key=val3';
$values = array();
$nv_strings = explode ('&', $payload);
foreach ($nv_strings as $s) {
$nv = explode ('=', $s, 2);
$name = urldecode ($nv[0]);
$value = (isset ($nv[1]) ? urldecode ($nv[1]) : null);
$values[] = array ($name => $value);
}
print_r ($values);
// Array
// (
// [0] => Array ([key] => val1)
// [1] => Array ([key] => val2)
// [2] => Array ([key] => val3)
// )
You may want to consolidate the duplicate keys into subarrays:
<?php
$payload = 'key1=val1&key1=val2&key2=val3';
$values = array();
$nv_strings = explode ('&', $payload);
foreach ($nv_strings as $s) {
$nv = explode ('=', $s, 2);
$name = urldecode ($nv[0]);
$value = (isset ($nv[1]) ? urldecode ($nv[1]) : null);
if (isset ($values[$name])) {
if (is_array ($values[$name])) {
$values[$name][] = $value;
} else {
$values[$name] = array ($values[$name], $value);
}
} else {
$values[$name] = $value;
}
}
print_r ($values);
// Array
// (
// [key1] => Array ([0] => val1
// [1] => val2)
// [key2] => val3
// )
You can simplify the code somewhat by always using subarrays:
<?php
$payload = 'key1=val1&key1=val2&key2=val3';
$values = array();
$nv_strings = explode ('&', $payload);
foreach ($nv_strings as $s) {
$nv = explode ('=', $s, 2);
$name = urldecode ($nv[0]);
$value = (isset ($nv[1]) ? urldecode ($nv[1]) : null);
if (isset ($values[$name])) {
$values[$name][] = $value;
} else {
$values[$name] = array ($value);
}
}
print_r ($values);
// Array
// (
// [key1] => Array ([0] => val1
// [1] => val2)
// [key2] => Array ([0] => val3)
// )
It is documented completely in PHP Documentation for the function parse_str If the output does not work for your particular use case, then you must use another function, or create your own. The key here is that this function parses the string into variables.
parse_str — Parses the string into variables
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
To parse the string you provided, this would work:
$payload = 'data.name=value';
$map = array();
$vals = preg_split('/=/', $payload);
$i= 0;
while($i < count($vals)) {
$map[$vals[$i]] = $vals[++$i];
$i++;
}
var_dump($map);