I am working on a project in which I will get an array.
When I use print_r($arr) it looks like this:
Array
(
[0] => games,
[1] => wallpapers,
.....
)
What i want to do is that i want it's value to be in an array like array('games','wallpapers') and save it to a file called data.txt using file_put_contents.
I did it once myown using implode() but sometimes it gets error. Is there a good way?
You need to serialize it and save it to a file. You can do it as a comma-separated values using implode(), or as a json string using json_encode() or using serialize(). All three of those links have excellent documentation and examples.
If you still have troubles, please edit your question with more specific details and the code you've worked on so far.
Try this,
<?php
$a=array
(
0 => 'games',
1 => 'wallpapers'
);
$str= implode(',',$a);
file_put_contents('data.txt', $str);
?>
data.txt
games,wallpapers
To retrieve the values, use array_values(). To store this array to disk, first serialize(), then store the output anyway you like - file_put_contents is the simplest way I believe.
Related
I am trying to read string in session array.
Here is the code I entered $fruit_type into my session:($number is 2622232 here)
$_SESSION['fruit'][$number]=$fruit_type;
When I used print_r($_SESSION['fruit']), I get the following array:
Array ( [2622232] => [] => apple )
My question is how can I get the string "apple"? My editor give me error message when I tried to use $_SESSION['fruit'][$number][] to read string.
Any idea about my situation?
The only way to get that print_r() output is with an empty string as key [''], so you need to find where you do that and fix it. However you can access it:
echo $_SESSION['fruit'][2622232][''];
$_SESSION['fruit'][$number][] is wrong as you don't pass an index. Something like $_SESSION['fruit'][$number][0] should work.
You can find more information about arrays in the PHP documentation (here the example that solves your problem)
I have a txt file that contains an array like this:
array (
0 => 'jack',
1 => 'alex'
)
I want to use this array in my PHP code but it is not working as on this example which returns a
$list= file_get_contents(myfile.txt);
echo $list[0];
How can I convert it ?
Rather have the array serialized or json_encoded, inside that file.
Then, when reading it, just unserialize or json_decode in $list
Example:
$list = unserialize(file_get_contents(myfile.txt));
To answer the quextion - eval looks like it will handle the array (Array has been output with var_export ?)
BUT exec'ing unknown code is a bad idea, W0rldart has the better ways to do it (json would be my preference)
I have text file containing values like this:
varname:
{
varname2: value
varname3:
{
varname4: value
}
}
I need to get this somehow into php array like this:
array(
varname => array
(
varname2 => value
varname3 => array
(
varname4 => value
)
)
)
How can i do this?
I have tried looping through file and trying to make values like that but it gets very tricky when there is multiple level array. Spent many hours without luck...
I suggest you (if you can) to change your file format to a JSON format, that is very similar to your format now:
{"varname":{"varname2":"value","varname3":{"varname4":"value"}}}
Then you can read the file and use json_decode to obtain the array in a very simple form. Here I write the code for decode json to array and echo it:
$s = file_get_contents('datos.js');
$ar = json_decode($s, true);
print_r($ar);
It depends on how much of a hack you want it to be. If you have a true defined format and want to be strict you'd start with a lexer. See http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/ or https://github.com/nikic/Phlexy
On the other hand you could also make it in two steps (depending on how complicated the now shown use cases are).
Replace all leading spaces and replace : \n{ with : { for easier parsing.
Write a recursive parsing function. In every line everything before : is the variable name, everything after the value. If the value is { to a recursion until } and use the result as the value.
So I would like to take a string like this,
q=Sugar Beet&qf=vegetables&range=time:[34-40]
and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.
I want it to look like this
['q'] => ['Sugar Beets],
['qf'] => ['vegetables']
After using urlencode I get
q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D
Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.
After this, the plan was to take the two array and combine them with array_combine().
So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.
PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.
You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():
$str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
parse_str($str, $params);
print_r($params);
Produces the output:
Array
(
[q] => Sugar Beet
[qf] => vegetables
[range] => time:[34-40]
)
You could use the parse_url() function/.
also:
parse_str($_SERVER['QUERY_STRING'], $params);
Given this in the Smarty template:
<pre>{$user->settings['sendStats']|#print_r:1}</pre>
The output in the browser is this:
Array
(
['period'] => daily
['ofPeriod'] => year
['points'] => 1000
)
Doing any of these:
<pre>{$user->settings['sendStats']['period']|#print_r:1}</pre>
<pre>{$user->settings['sendStats'][ofPeriod]|#print_r:1}</pre>
<pre>{$user->settings['sendStats'].points|#print_r:1}</pre>
<pre>{$user->settings.{'sendStats'}.{'period'}|#print_r:1}</pre>
<pre>{$user->settings.{sendStats}.{period}|#print_r:1}</pre>
with or without the |#print_r:1 gives no output in the browser.
I also tried assigning $user->settings to a Smarty variable and I get the exact same result (as expected).
How do I access the elements of the $user->settings['sendStats'] array?
{$user->settings.sendStats.period|#print_r:1} should work just fine. Also have a look at the Variables page in the docs…
The array values itself are not arrays (your array is not multidimensional), so you should drop the |#print_r:1 and you should be fine. Should look something like:
<pre>{$user->settings['sendStats']['period']}</pre>
Finally figured it out. The array keys contained single quotes, so the answer would have been:
{$user->settings['sendStats']["'period'"]}
I fixed it so the keys didn't contain quotes anymore.