Decode serialized cookie and loop options - php

I store form elements as serialized data in a cookie.
On another page I want to collect this cookie but the cookie contains this string:
form_key=kcE3W2vzParNhPN5&options%5B1508%5D=2025&options%5B1509%5D=1234&options%5B1510%5D=5678&options%5B1511%5D=&options%5B1512%5D=&options%5B1513%5D=&productId=59891
%5B and %5D are brackets I figured, but how can I look through all these options in the string and get their ID + value into an array with PHP.
So from above string I would like to create an array with:
arr = array (
[1508] = '2025';
[1509] = '1234';
[1510] = '5678';
[1511] = '';
[1512] = '';
);

I think what you want is parse_str():
$str = "form_key=kcE3W2vzParNhPN5&options%5B1508%5D=2025&options%5B1509%5D=1234&options%5B1510%5D=5678&options%5B1511%5D=&options%5B1512%5D=&options%5B1513%5D=&productId=59891";
$output = array();
parse_str($str, $output);
print_r($output); // $output['options'] will contain your array you're looking for.
See execution here:
Array
(
[form_key] => kcE3W2vzParNhPN5
[options] => Array
(
[1508] => 2025
[1509] => 1234
[1510] => 5678
[1511] =>
[1512] =>
[1513] =>
)
[productId] => 59891
)

Related

convert sql array value result to array php

I have a column of datatype array in sql like:
This value is received as :
$customlabel = "{new,\"tree test123\",de}"
I tried json_decode($customlabel, TRUE) to get it into array. But this just returns empty string
This is not valid JSON. You can not decode the JSON. So you can consider it as a string and my answer would be..
$customlabel = html_entity_decode("{new,\"tree test123\",de}");
$customlabel = str_replace(array('{', '}'), '', $customlabel);
$customlabel = explode(',', $customlabel);
$customlabel = array_map('strval', $customlabel);
print_r($customlabel);
Your output will be...
Array ( [0] => new [1] => "tree test123" [2] => de )

Create Array newline and add values into multidimensional Array

I have a set of values as a string, like so:
MyCustomProductID1
MyCustomProductID2
Then I proceed to create an array out of these values with explode( "\n", $myProductIdString)
Now I have additional data (strings) that I want to combine with the value from my first array. I want that simple array into a multidimensional one:
Array
(
[0] => Array
(
[id] => MyCustomProductID1
[url] => http://example.com/MyCustomProductID1.jpg
)
[1] => Array
(
[id] => MyCustomProductID2
[url] => http://example.com/MyCustomProductID2.jpg
)
)
How do I get that first array into a multidimensional one and push data along with it?
Instead of direct assigning values to array use loop-
<?php
$str = "MyCustomProductID1
MyCustomProductID2";
$arr = explode("\n", $str);
$result = [];
$url_array = ["http://example.com/MyCustomProductID1.jpg", "http://example.com/MyCustomProductID2.jpg"];
for($i=0;$i<count($arr);$i++){
$result[$i]['id'] = $arr[$i];
$result[$i]['url'] = $url_array[$i];
}
print_r($result);
?>

pull dynamic element in single array

I am trying to pull dynamic element in single array but result is not showing properly
Ex:
$array =array();
$element="'abc1','abc2'";
$array=array('abc',$element);
//I want result like that:
array[
[0]=>abc,
[1]=>abc1,
[2]=>ab
]
If you need to parse a string of elements to an array you can use one of the csv functions. You may then merge your arrays.
$array = array('abc');
$string_elements = "'abc1','abc2'";
$array_elements = str_getcsv($string_elements, ',', "'");
$array = array_merge($array, $array_elements);
var_export($array);
Output:
array (
0 => 'abc',
1 => 'abc1',
2 => 'abc2',
)
Alternatively to add each array element to the end of another array you can push them like so using a splat:
array_push($array, ...$array_elements);
According to my understanding, $element is storing string not an array so even if you try to get output it will display in following format
Array
(
[0] => abc
[1] => 'abc1','abc2'
)
Instead of this you can store array in $element variable and use array_merge() function to get required output e.g.
$element = array('abc1','abc2');
$array = array('abc');
$result = array_merge($array,$element);
// Output
Array
(
[0] => abc
[1] => abc1
[2] => abc2
)

How to retrieve array values into individual variables

I have an API which returns a response in form of an array. I want to extract the elements from this array and save them in my database. I have tried using the explode function but it seems I am missing something. Below is an exact sample response from the retrieve.
Array
(
[Response] => Array
(
[external_reference] => bablaba
[withdraw_request_id] => babalalal
[amount] => bababababa
[status] => ababababab
[message] => ababababa.
[new_balance] => babababa
[amount_sent] => ababababa
[currency_sent] => ababababa
[charge_amount] => ababababa
[charge_currency] => babababa
[currency] => abababaab
)
)
What's the point to duplicate the variables?
When you want to save the amount for exemple use $array['response']['amount']
You have an array Response inside the array $Array. In order to convert array element values into variables. You must navigate inside $Array and inside Response to do so you write : $bigArray['smallArray']['element'].
$external_reference = $Array['Response']['external_reference'];
$withdraw_request_id = $Array['Response']['withdraw_request_id'];
$amount = $Array['Response']['amount'];
$status = $Array['Response']['status'];
$message = $Array['Response']['message'];.
$new_balance = $Array['Response']['new_balance'];
$amount_sent = $Array['Response']['amount_sent'];
$currency_sent = $Array['Response']['currency_sent'];
$charge_amount = $Array['Response']['charge_amount'];
$charge_currency = $Array['Response']['charge_currency'];
$currency = $Array['Response']['currency'];
To learn more about multidimensional arrays read: this

PHP string to nested / multidimensional array

I have this example php string:
$string = "#[item_1][door] #[mozart][grass] = yes #[mozart][green] = no #[mozart][human] #[blue][movie]=yes #[item_1][beat] = yes #[item_1][music] = no
";
now $string idented just to easy view:
#[item_1][door]
#[mozart][grass] = yes
#[mozart][green] = no
#[mozart][human]
#[blue][movie]=yes
#[item_1][beat] = yes
#[item_1][music] = no
I want to know how can i get this string ( or other string following this style ) and transform in an array that looks like:
Array
(
[item_1] => Array
(
[door] => Array
(
[mozart] => Array
(
[grass] => yes
[green] => no
[human] => Array
(
[blue] => Array
(
[movie] => yes
)
)
)
)
[beat] => yes
[music] => no
)
)
What i tried
I tried to use and recursive function to create an nested array but i can't have access to the array pointer ( in deep levels ) in recursive functions.. don't know why.. maybe is the wrong patch to the answer.
thank you,
OK, I hope you still need this, because I wasted more time than I'd like to admin getting this right :)
Basically, my approach was to first manipulate the string into the format [set][of][keys]=value, and then loop through the string of keys and comparing them with the last set of keys to create the correct key hierarchy. I used eval because it's easier, but you can write a replacement function if you can't stomach seeing that function in your code:
//FIRST WE GET THE STRING INTO EASIER TO WORK WITH CHUNKS
$original_string = "#[item_1][door] #[mozart][grass] = yes #[mozart][green] = no #[mozart][human] #[blue][movie]=yes #[item_1][beat] = yes #[item_1][music] = no ";
$cleaned_string = str_replace('] #[','][',$original_string);
/* This results in clusters of keys that equal a value:
#[item_1][door][mozart][grass] = yes #[mozart][green] = no #[mozart][human][blue][movie]=yes #[item_1][beat] = yes #[item_1][music] = no
OR (with line breaks for clarity):
#[item_1][door][mozart][grass] = yes
#[mozart][green] = no
#[mozart][human][blue][movie]=yes
#[item_1][beat] = yes
#[item_1][music] = no */
//break it up into an array:
$elements = explode('#',$cleaned_string);
//create a variable to compare the last string to
$last_keys = "";
//and another that will serve as our final array
$array_of_arrays = array();
//now loop through each [item_1][door][mozart][grass] = yes,[mozart][green] = no, etc
foreach($elements as $element){
if ($element==""){continue;} //skip the first empty item
//break the string into [0] = group of keys and [1] the value that terminates the string
//so [item_1][door][mozart][grass] = yes BECOMES [item_1][door][mozart][grass], AND yes
$pieces = explode('=',str_replace(array('[',']'),array("['","']"),trim($element)));
//now compare this set of keys to the last set of keys, and if they overlap merge them into a single key string
$clean_keys = combine_key_strings($pieces[0],$last_keys);
//set the new key string the value for the next comparison
$last_keys = $clean_keys;
//and (ugly, I know) we use an eval to convert "[item_1][door][mozart][grass]='yes'" into a properly keyed array
eval("\$array_of_arrays".$clean_keys." = '".trim($pieces[1])."';");
}
//now dump the contents
print_r($array_of_arrays);
//THIS FUNCTION COMPA
function combine_key_strings($new,$old){
//get the key that starts the newer string
$new_keys = explode('][',$new);
$first_key = $new_keys[0].']';
//see if it appears in the last string
$last_occurance = strrpos ($old,$first_key);
//if so, merge the two strings to create the full array keystring
if (is_int($last_occurance)){
return substr($old,0,$last_occurance).$new;
}
return $new;
}
This should spit out your correctly nested array:
Array
(
[item_1] => Array
(
[door] => Array
(
[mozart] => Array
(
[grass] => yes
[green] => no
[human] => Array
(
[blue] => Array
(
[movie] => yes
)
)
)
)
[beat] => yes
[music] => no
)
)
Good night!

Categories