How to get value of param thats declared a few times - php

I'm building a PHP querying a mongodo database. I need to retreive the value of a param from the url, and there is potentially more than one.
An example url would look like this
http://localhost/api/v1/report-01?type=EE&type=ER
How would I retrieve the two values from type.
At the moment I'm only get one, and it's the last one.
if (isset($params["TYPE"]) && in_array($params["TYPE"], ["EE", "ER"])) {
$matchPipeline["TYPE"] = $params["TYPE"];
echo "Printing Variables";
echo $params["TYPE"];
}
The code is only printing ER.
I have no access to the frontend, only the backend so I can't change the URL structure

How would I retrieve the two values from type.
With [ ] after your key
api/v1/report-01?type[]=EE&type[]=ER

You can achieve this by accessing directly to global $_SERVER variable and using preg_match_all, here is an example:
<?php
preg_match_all('/type=(\w+)/', $_SERVER['QUERY_STRING'], $matches);
var_dump($matches[1]);

Just create this function query to array and split the value
function queryToArray($q)
{
$arr = [];
foreach(explode("&", $q) as $l)
{
$b = explode('=', $l);
if ( (is_array($b) && count($b) > 0) )
$arr[$b[0]] = $b[1];
}
return $arr;
}
$arr = parse_url($url_string);
print_r(queryToArray($arr['query']);

Related

link a value from an array to another in PHP

I'm trying two combine two arrays based on the values names.
Here what I'm trying to do :
$array1 = ("fifa21","pes21","halflife2","carma2");
$array2 = ("fifa21_cover","pes21_cover","halflife2_cover");
I want to loop through both arrays and if value from array1 match value from array 2 it will list both values like this :
fifa21 - fifa21_cover
pes21 - pes21_cover
halflife2 - halflife2_cover
carma2 - default_cover
if not find anything in the array2, a default cover will be used.
Note: the arrays will be filled dynamically based in a scanDir (two different folders search) and the arrays can be sorted differently than shown in the example above.
This code will loop through array1 and check to see if the item cover exists in array2, if it does then it will echo out in the format you wanted.
$array1 = array("fifa21","pes21","halflife2","carma2");
$array2 = array("fifa21_cover","pes21_cover","halflife2_cover");
foreach ($array1 as $item) {
if (in_array($item."_cover", $array2)) {
echo "<p>".$item." - ".$item."_cover</p>\n";
} else {
// use default cover...
}
}
(because it is lunch time and I need to write some code)
Given two arrays:
$array1 = ["fifa21", "pes21", "halflife2", "carma2"];
$array2 = ["fifa21_cover", "pes21_cover", "halflife2_cover"];
A function such as this can walk through and look for items that start with those values:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$items = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key));
if (count($items) === 1) {
$output[$key] = reset($items);
return;
}
if (count($items) === 0) {
$output[$key] = 'default_cover';
return;
}
throw new RuntimeException('More than one item found starting with key ' . $key);
}
);
return $output;
}
When called as:
print_r(merge_arrays($array1, $array2));
It will output:
(
[fifa21] => fifa21_cover
[pes21] => pes21_cover
[halflife2] => halflife2_cover
[carma2] => default_cover
)
For your use-case, it might be overly complicated when compared to a for loop, but it does the job.
Another version that more-blindly assumes only a one-to-one match could use the ?? operator for a null check, although I wouldn't recommend this. The more terse and compact that code looks, the more I find that it is usually very hard to reason about, especially in the future:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$output[$key] = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key))[0] ?? 'default_cover';
}
);
return $output;
}
All code snipping provided works, however if the array values have extension it always assumes the default cover. I can figure it how using my code by removing the extension for compare purpose, and then I add it back.
Inside my loop I use this :
$keyvaluetemp = substr($keyvalue, 0, strrpos($keyvalue, "."));
the above it inside my first ForEach (where I check the first array), and then in the covers array I remove the "_cover" by nothing :
$keyvalue2temp = (str_replace("_cover", "",$keyvalue2));
then I use the following code inside the second ForEach to add the data to a DB:
// if fantart match the game file name so we associate it to the game and save to the DB
if ( stripos ( $keyvalue2temp , $keyvaluetemp ) !== FALSE )
{
$sql = "UPDATE listgames SET FanArt='$keyvalue2' WHERE Name='$keyvalue'";
$con->exec($sql);
}
// if fanart is empty we add a default picture
$checkifempty = "SELECT `FanArt` FROM `listgames` WHERE `Name` = '$keyvalue'";
$runsql = $con->query($checkifempty);
$row = $runsql->fetch(PDO::FETCH_ASSOC);
$fanartkey = $row['FanArt'];
if($fanartkey == '')
{
$sql = "UPDATE listgames SET FanArt='nopic.JPG' WHERE Name='$keyvalue'";
$con->exec($sql);
}
Later in my code I print the results from the DB. I don't know if this is the best approach, however it does exactly what I want :)

How to substr array in php?

I have array, I want to make selection in it, but before do selection
I want to take 2 numbers in front of each values in array:
$myarray[2] = array(62343,62444,62343,08453,62333);
I want something like this:
$arraysubstr = substr($myarray[2],0,2)
if(($arraysubstr) < 62) //not work (work for first array value)
{
redirect
}else{
no problem
}
I thank all those who want to comment
You can use array_walk() function. It takes two parameters one is array and another is a function. You can perform any operation you want using the function on your array.
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");
Use array_walk() function to walk through the array. It returns true on success and false on failure. Its accepts two parameters one is array and other is callback fnction.
$myarray[2] = array(62343,62444,62343,08453,62333);
function func($value,$key) {
$item = substr($value,0,2);
if(($item) < 62)
{
echo 'redirect';
}else{
echo 'no problem';
}
}
array_walk($myarray[2], "func");

How Can I Select Data by Name From Array in PHP?

I have an array like this:
Array(
[0]=>Array([uploaderName]=>x[uploadedImageName]=>k6gIjfO[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[1]=>Array([uploaderName]=>x[uploadedImageName]=>byUTyJo[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[2]=>Array([uploaderName]=>x[uploadedImageName]=>oSVEnNk[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[3]=>Array([uploaderName]=>x[uploadedImageName]=>Dj7GRYS[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[4]=>Array([uploaderName]=>x[uploadedImageName]=>upsb8IC[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[5]=>Array([uploaderName]=>x[uploadedImageName]=>YoEEzGi[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[6]=>Array([uploaderName]=>x[uploadedImageName]=>st3dLNs[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[7]=>Array([uploaderName]=>x[uploadedImageName]=>LBNpiIG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[8]=>Array([uploaderName]=>x[uploadedImageName]=>mFYDmBG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[9]=>Array([uploaderName]=>x[uploadedImageName]=>z03kSx1[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
)
I want to get any image's data from this array.
Example: When user shows uploadedImageName == jCPjeWv, I wan't to get who is it's uploader.
Simple, just use foreach
$arr = array(/* content here */);
foreach($arr as $value){
if($value['uploadedImageName'] == 'jCPjeWv'){
echo $value['uploaderName'];
break;
}
}
Just for fun, here's another way:
echo array_column($array, 'uploaderName', 'uploadedImageName')['jCPjeWv'];
Get an array of uploaderName with the index set to uploadedImageName
Access the index using the uploadedImageName 'jCPjeWv'
Obviously to do it multiple times you would want to actually create a new array:
$images = array_column($array, 'uploaderName', 'uploadedImageName');
echo $images['jCPjeWv'];
If you want to access the other values as well, then use null instead of uploaderName:
$images = array_column($array, null, 'uploadedImageName');
echo $images['jCPjeWv']['uploaderName'];
echo $images['jCPjeWv']['uploaderIp'];
NOTE: These ways only work if the uploadedImageName is unique.
A foreach is possible, but I think it's important to learn the array functions as well so I'm just going to put this example here.
$uploadedImageName = 'jCPjeWv';
$filtered = array_filter($array, function($value) use ($uploadedImageName) {
return ($value['uploadedImageName'] == $uploadedImageName);
});
This will return a $filtered with the other arrays removed since their $value['uploadedImageName'] will not equal $uploadedImageName.
For more info check out the http://php.net/manual/en/function.array-filter.php manual.

Assign GET variable to another in PHP when you know part of the name of the GET variable

I have some problems with GET variable in PHP.
I need to assign a GET variable to a normal variable in PHP, but the name of the GET variable is not always the same name.
Ex. $telf=$_GET['t_1'].
But can be $_GET['t_6'], $_GET['t_18'].
There's any way to assign all possible names of $_GET['t_XX'] to another variable?
You could use preg_grep.
With preg_grep you can get all keys in $_GET that start with 't_'. Then you walk over these values, and print (or do whatever you want) with the key + value.
Please see this example:
$keys = preg_grep("/^t_.*/", array_keys($_GET));
foreach($keys as $key) {
echo $key.' holds value '.$_GET[$key].PHP_EOL;
}
Another option a bit lighter in resources is using strpos on the keys
foreach ( $_GET as $keys => $values ) {
if ( strpos( $keys, 't_' ) !== false ) {
$final_var = $values;
}
}

Get all the current Session Variables that being with a certain string

All,
I've created a whole bunch of session variables based on an id. So for example I can have the following variables:
$_SESSION['test_variable_1'];
$_SESSION['test_variable_2'];
$_SESSION['test_variable_3'];
I'd like to read all of these with PHP and basically return a JSON array of the id at the end of the variable. So I'd like 1, 2 and 3 returned in this example. The session variables I wnat to look at will always start with test_variable_ and followed by the ID I want to obtain. What is the best way to do this?
Thanks!
While the better idea would've been to just create a sub-array within the session superglobal, so that you could use $_SESSION['test_variable'][1] and the like, you can use something like preg_grep to scan for these keys:
$keys = array_keys($_SESSION);
$matches = preg_grep('/^test_variable_\d+$/', $keys);
foreach($matches as $key) {
$digit = substr($key, 13); // extract the digit.
echo $_SESSION[$key];
}
Something like this?
$ids = array();
foreach($_SESSION as $var => $value) {
if (strpos($var, 'test_variable_') === 0) {
$ids[] = str_replace('test_variable_', '', $var);
}
}

Categories