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.
Related
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.
I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.
There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.
You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);
You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.
Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.
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
)
Here's an array:
array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
)
As you can see, the array goes three levels deep.
Here are two strings:
1. 'csv/path'
2. 'csv/lines/0
Using / as the delimiter, string 1 will get '/file.csv' and string 2 will get 'line1'. I've been thinking about using a recursive function, but I just don't know yet how to go about it.
The idea is I won't know which array key I'm accessing. I'm working on creating a generic function that will take a string as input and return the respective value in the array.
Demo
Just iterate through each key from the string given, setting the new array to pull from as the found element in the given array. You should add error handling.
<?php
$array = array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
);
echo extractData($array, 'csv/path'); // echoes /file.csv
echo extractData($array, 'csv/lines/0'); // echoes line1
function extractData($array, $string){
$keys = explode('/', $string);
$data = $array;
foreach ($keys as $key){
$data = $data[$key];
}
return $data;
}