How to extract PHP array values and remove data - php

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

Related

PHP - Compare array and output found values [duplicate]

I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo

Broke string into vars with variable position

I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));

How to separate a php array items by prefix

I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo

PHP get parameters from URL and convert to array

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.

Fetch the value from the key PHP

I have a wordy value array without explisit keys for speed reason. And the keys are populated as numeric keys 0-N automatically:
$array = array('Good old days', 'Bad old days', ....);
The form is filled up with expected key|value pairs:
key=0, value=Good old days
or
<option value="0">Good old days</option>
which is good as I don't want to have long wordy keys.
Now the issue part is, I know how to fetch the key, but I can not find a way how to display the value out of the given key. Maybe because I have to loop for a condition and than the key is grabbed if the condition met.
How do you grab the value from the given key?
Any hint would be very much appreciated.
UPDATE:
//If keys are wordy: http://fonts.googleapis.com/css?family=Quattrocento|Droid+Sans|Yanone+Kaffeesatz
$gwf_settings = array(
'base_font',
'article_title',
'site_name',
'site_slogan',
);
$gwfs = array();
foreach($gwf_settings as $key => $gwf_font) {
//dsm('KEYS: '. $key);
// parent form to check condition if we are using gwf
if (theme_get_setting($gwf_font) == 'gwf') {
$values = $gwfs[theme_get_setting($gwf_font .'_gwf')];
dsm('KEY2: '. theme_get_setting($gwf_font .'_gwf')); //ok, we have the gwf key
dsm('VALUES: '. $values); // BLANK
$gwfs[] = str_replace(' ', '+', $values);
}
}
$google_web_fonts = implode('|', $gwfs);
I seem to get stucked with "values".
UPDATE 2, in case useful to anyone, or any betterment:
$gwf_settings = array(
'base_font',
'article_title',
'site_name',
'site_slogan',
);
$gwf_gwf = array(
'base_font_gwf',
'article_title_gwf',
'site_name_gwf',
'site_slogan_gwf',
);
foreach($gwf_settings as $key => $gwf_font) {
if ( theme_get_setting($gwf_font) == 'gwf' ) {
$gwfs = array();
foreach ($gwf_gwf as $k => $gwf_setting) {
$s = theme_get_setting($gwf_setting);
$fonts = get_gwf();
if ( $s ) {
foreach ($fonts as $f => $val) {
if ( $f == $s ) {
$gwfs[] = str_replace(' ', '+', $val);
}
}
}
}
}
}
$google_web_fonts = implode('|', $gwfs);
// The final output will be just like with wordy key version:
//http://fonts.googleapis.com/css?family=Oswald|Yanone+Kaffeesatz|Droid+Sans
echo $array[0] will print 'Good old days'.
If you have the key, you can use it the same as always:
$array[$key]

Categories