so I have this variable $_GET which receives the value such as
set=QnVzaW5lc3M=|RmluYW5jZQ==
The values are base64 enconded using base64_encode() and then separated by a delimiter '|'. I'm using implode function to generate the value of the set variable.
Now, the question is, how can I get the values from the set variable into an array and base64 decode them as well ?
Any suggestions are welcome.
I tried this :-
$test = array();
$test = explode('|', $_GET['set']);
var_dump($test);
This throws the value which is not usable.
But this made no difference.
$data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
$result = array_map(
'base64_decode',
explode('|', $data)
);
var_dump($result);
This should work using foreach:
// Set the test data.
$test_data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
// Explode the test data into an array.
$test_array = explode('|', $test_data);
// Roll through the test array & set final values.
$final_values = array();
foreach ($test_array as $test_value) {
$final_values[] = base64_decode($test_value);
}
// Dump the output for debugging.
echo '<pre>';
print_r($final_values);
echo '</pre>';
The output is this:
Array
(
[0] => Business
[1] => Finance
)
Related
Example
I have CSV file that contains data of random number example data in CSV :
639123456789,73999999999,739222222222,839444444444,8639555555555....more
So, if I upload it, I want it to explode in a variable or in an array as long as I get the specific data. example of data I want to get is all 2 first line starting at 73 be extract so meaning all numbers that start with 73 only.
Example: 73999999999,739222222222
I have tried it by using only 1 number using split,substr and explode function but my problem is if the user input a CSV bulk data with no limit.
You can use substr() and loop through your array deleting the elements that do not match.
$str = '639123456789,73999999999,739222222222,839444444444,8639555555555';
$array = explode(',', $str); //Convert your string to an array.
$searchString = '73'; //Set the value your looking for.
foreach($array as $key=>$value){
if(substr($value, 0, 2) != $searchString){ //This will test first two characters.
unset($array[$key]);
}
}
$array = array_values($array);
print_r($array);
This will output:
Array
(
[0] => 73999999999
[1] => 739222222222
)
Updated
This will make a new array with only the numbers you want in it, leaving the original array untouched.
$str = '639123456789,73999999999,739222222222,839444444444,739222222222,839444444444,839444444444,73999999999';
$array = explode(',', $str);
$searchString = '73';
foreach($array as $key=>$value){
if(substr($value, 0, 2) == $searchString){
$results[] = $value;
}
}
print_r($results);
I am being passed inconsistent data. The problem is the individual rows of $data_array are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order_array, create a new $data_array_new by reordering the data in each "row" into the same sequence as $order_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
$data_array_new = [];
foreach ($data_array as $index => $data) {
$data_array_new[$index] = [];
foreach ($order_array as $key) {
if (isset($data[$key])) {
$data_array_new[$index][] = $data[$key];
} else {
$data_array_new[$index][] = 'NA';
}
}
}
You can view the original incoming data here: https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats
Here is the answer from : Andreas
Use json_decode on the string with the second parameter true and you get a associative array as output.
$url = "https://api.iextrading.com/1.0/stock/market/batch?
symbols=aapl,tsla,ge&types=quote,earnings,stats";
$arr = json_decode(file_get_contents($url), true);
Var_dump($arr);
See here;
I copied the string from the page and posted it as $str.
https://3v4l.org/duWrI
Two steps is all that is needed.
I have a string like this:
$string = '[miniTrack, boxTrack]'
I want to turn it into an array of variables like this:
$array = [$miniTrack, $boxTrack];
So that I can perform loops and iterations through the variable. And access the variables they are referencing.
I tried eval but I can't figure out how to convert it to a PHP Variable.
I KNOW THAT THIS IS NOT IDEAL, THE STRUCTURE OF THE DATABASE THIS IS PULLING FROM CAN'T BE ADJUSTED UNFORTUNATELY
Your question starts unusually, because you show an array containing a single string that is comma-separated, rather than an array of individual strings.
You could try something like the following:
$arr = [];
$string = ['miniTrack, boxtrack'];
//split the one string into an array, trimming spaces
$vars= array_map('trim', explode(',', $string[0]));
foreach($vars as $var) {
$arr[] = $var; //add the var to the array
}
print_r($arr);
Array
(
[0] => miniTrack
[1] => boxtrack
)
And if you need to create a variable for each item, you can create "variable variables":
foreach($vars as $var) {
$my_var = $$var; //variable variable
}
It should be as easy as the following:
preg_match_all('~(\w+)~','[miniTrack, boxTrack]', $matches);
foreach($matches[1] as $var)
{
print $$var;
}
You can convert your strings to array like this. It may be not ideal but you can use try this.
$string = '[miniTrack, boxTrack]';
$string = str_replace(array('[',']'),array('', '' ), $string);
$array = explode(',',$string);
Here you can iterate your array whatever you want.
well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help
I have an array with $post_id as keys. When save the $data, I saved it as a string:
foreach( $data as $post_id => $details )
$string .= "-pid-$post_id-$details";
When use the data, I need to convert it back to array with $post_id as key and $details as value. How to explode it when I don't know what is the $post_id ?
Don't do it this way. if you need to serialize a string use json_encode():
$string = json_encode($data);
Then, when you need to decode it again:
$data = json_decode($string);
Safe and easy.
Here's the PHP reference: json_encode()
php has a method called serialize which will take an array (such as $_POST) and convert it to a string that can then be recreated into an array with unserialize
<?php
// $_POST looks like this for example:
// $_POST['value'] = 100;
$string = serialize($_POST);
echo $string; // Prints '"a":1:{s:5:"value";s:3:"100";}'
$data = unserialze($string);
print_r($data); // Prints Array[0] ( 'value' => '100' )
?>
I won't lecture about not sanitizing user input, but SANITIZE USER INPUT.
serialize
unserialize
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field. -- from php docs
You would need to explode the string using
explode ( string $delimiter , string $string [, int $limit ] )
This will return your data as an array
for example
foreach($data AS $post_id => $details) {
$string .= "|||$post_id||$details"
}
then to get your data back out of string
$newArray = explode('|||', $string);
foreach($newArray AS $key=>$val){
$holding = explode('||', $val);
$finalArray[$holding[0]] = $val;
}
Now you will have an array with key being the id and val being the details for each of the items in the string.
EDIT:
Or use serialize and unserialize like Brombomb suggested.
If I understand your question...
$temp = explode('-pid-', $string);
array_shift($temp);
foreach ($temp as $item) {
list($post_id, $value) = explode('-', $item);
$data[$post_id] = $value;
}
json_encode and associated json_decode may be a better option for "stringifying" your data in the first place. However, there may be a legitimate reason for doing it the way you've chosen to do it.