PHP get parameters from URL and convert to array - php

CASE:
I'm trying to get ordered items and quantity from another page, so I'm passing it using GET (http://foo.bar/?view=process-order&itm=1&qty=1000...), then I must to take this parameters and convert to an multidimensional array following this sequence:
EXPECTED:
URL will be: http://foo.bar/?view=foo-bar&itm=1&qty=1000&itm=2&qty=3000&itm=3&qty=1850
[0]=>
[itm]=>'1',
[qty]=>'1000',
[1]=>
[itm]=>'2',
[qty]=>'3000',
[2]=>
[itm]=>'3';
[qty]=>'1850',
etc.
CODE:
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode( '&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$items = implode(",", $items); //Implode to a string and separate with commas
list($key,$val) = explode(',',$items); //Explode and remove the commas
$items = array($key => $val); //Rebuild array
ACTUAL RESULT:
[itm=1] => [qty=1000]
ACTUAL BEHAVIOUR:
Result leave only the first element in the array and make it like array({[itm=1]=>[qty=1000]}) that anyway isn't what I need.
Even If I've read much pages of PHP docs can't find the solution.
Thanks to all who can help

Your statement list($key,$val) = explode(',',$items); will only fetch the first two items in an array.
Here's a rewritten version
$chunks = explode('&', $_SERVER['QUERY_STRING']);
$items = array();
$current = -1; // so that entries start at 0
foreach ($chunks as $chunk) {
$parts = explode('=', $chunk);
if ($parts[0] == 'itm') {
$current++;
$items[$current]['itm'] = urldecode($parts[1]);
}
elseif ($parts[0] == 'qty') {
$items[$current]['qty'] = urldecode($parts[1]);
}
}
print_r($items);

Here is another version. I only modified the bottom part of your code (first 4 lines are untouched).
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode('&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$list = array(); // create blank array for storing data
foreach ($items as $item){
list($key, $val) = explode('=', $item);
if ($key === 'itm')
$list[] = ['itm' => $val];
else // qty
$list[count($list) - 1]['qty'] = $val;
}
Hope this helps.

Related

How to extract PHP array values and remove data

I have seen a bunch of ways, but none that seem to work. My array data is coming back like this.
Array
(
[0] => RESULT=0
[1] => RESPMSG=Approved
[2] => SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4
[3] => SECURETOKENID=253cad735251571cebcea28e877f4fd7
I use this:
<?php echo $response[2];?>
too get each out, that works. But I need to remove “SECURETOKEN=” so im left with just the number strings. I have been trying something like this with out success.
function test($response){
$secure_token = $response[1];
$secure_token = substr($secure_token, -25);
return $secure_token;
}
Also Im putting end number into a form input “Value” field. Not that that matters, unless it does?
Thanks
This is what I would do:
$keyResponse = [];
foreach ($response as $item) {
list($k, $v) = explode('=', $item, 2);
$keyResponse[$k] = $v;
}
Now you can easily access just the value part of each item based on the name:
echo $keyResponse['SECURETOKEN']; // output: 8cpcwfZhaH02qNlIoFEGZ1wO4
The advantage to this method is the code still works if the order of the items in $response changes
I get your secure token like this (tested):
<?php
$arr = array(
'RESULT=0',
'RESPMSG=Approved',
'SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4',
'SECURETOKENID=253cad735251571cebcea28e877f4fd7'
);
$el = $arr[2];
$parts = explode('=', $el);
echo '#1 SECURETOKEN is ' . $parts[1];
// This break just for testing
echo '<br />';
// If you wanted to, you could revise the whole array
$new = array();
foreach( $arr as $el ){
$parts = explode('=', $el);
$new[$parts[0]] = $parts[1];
}
// Which would mean you could then get your securetoken like this:
echo '#2 SECURETOKEN is ' . $new['SECURETOKEN'];

PHP filter links

i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}

match values from array with values of another array and return corresponding values in new array as loop

I'm having trouble finding a solution to the following problem.
I need to take the first value of one array ($split), find it in another array ($array) and return a corresponding value into a new array ($matched), then loop until all values in $split have been matched and returned (in order) to $matched.
I've annotated my code below to explain further.
<?php
$split = explode('/', '1/2/3');
// $split can be any length and any order
// EG. $split = explode('/', '1/2/3/66/4/9');
$result = $connection->query("SELECT id, filename FROM pages");
while ($row = $result->fetch_array()) {
$new_array[$row['id']] = $row;
}
foreach($new_array as $array) {
// take first value from $split
// match value with 'id' of $array
// return corresponding 'filename'
// set as first value of $matched
$matched = //
// loop until all values from $split have been matched
// and the corresponding filename has been added to $matched.
}
$join = implode('/', $matched); // join $matched as string.
?>
Let'see:
You have list of numbers (ids),
you have map: id -> filename,
you need filenames ( imploded by slash )
so:
<?php
// $split can be any length and any order
// EG. $split = explode('/', '1/2/3/66/4/9');
$split = explode('/', '1/2/3');
// NB!
$split = array_flip( $split );
$result = $connection->query("SELECT id, filename FROM pages");
/* I need exactly map id -> filename for implode() */
while ($row = $result->fetch_assoc()) {
$new_array[$row['id']] = $row['filename'];
}
$matched = array_intersect_key($new_array, $split);
$join = implode('/', $matched); // join $matched as string.
?>
Try the following example:
// ... some code
$matched = array();
foreach ( $split AS $key ) {
if ( isset($array[$key]) ) {
$matched[] = $array[$key];
}
}
return $matched;
// ... more code
I would build a mysql query this way:
SELECT id, filename FROM pages WHERE id IN(1,2,3,66,4,9) ORDER BY FIELD(id,1,2,3,66,4,9)
And then, in php:
while($row = $result->fetch_assoc()) {
$match[] = $row;
}

How to create multidimensional PHP array from this string?

I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?
You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}
You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.
$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories