Best way to write arrays to a file? [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I want to avoid writing to DB and use constants/array for lang files etc.
i.e:
$lang = array (
'hello' => 'hello world!'
);
and be able to edit it from the back office.
(then instead of fetching it from the poor db, i would just use $lang['hello']..).
what are you suggesting for the best and efficient way to pull it of?

the most efficient way i found looks like this:
build up your array in php somehow and export it into a file using var_export()
file_put_contents( '/some/file/data.php', '<?php return '.var_export( $data_array, true ).";\n" );
then later, wherever you need this data pull it like this
$data = include '/some/file/data.php';

Definitely JSON
To save it :
file_put_contents("my_array.json", json_encode($array));
To get it back :
$array = json_decode(file_get_contents("my_array.json"));
As simple as that !

Well if you insist to put the data into files, you might consider php functions serialize() and unserialize() and then put the data into files using file_put_contents.
Example:
<?php
$somearray = array( 'fruit' => array('pear', 'apple', 'sony') );
file_put_contents('somearray.dat', serialize( $somearray ) );
$loaded = unserialize( file_get_contents('somearray.dat') );
print_r($loaded);
?>

You can try json_encode() and json_decode().
$save = json_encode($array);
write contents of $save to file
To load lang use:
$lang = file_get_contents('langfile');
$lang = json_decode($lang, true);

Related

Taking data from multiline textbox and utilising the data submitted PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Trying to understand how I can take multi-line textbox data and then utilise it using PHP.
Within the textbox I want users to be able to write down the format "Website,URL" per line and then generate as a link.
A user would post multiple lines of text:
E.g
Microsoft,https://microsoft.com
Stackoverflow,https://stackoverflow.com
I understand that I would need to use the php explode to break down the line into an array but how can I seperate the data from within that array and then utilise each point of data in a list format? I've confused myself writing this, hoping someone can help!
Given this :
Microsoft,https://microsoft.com Stackoverflow,https://stackoverflow.com
Expected to got this :
array(
'Microsoft' => 'https://microsoft.com',
'Stackoverflow' => 'https://stackoverflow.com'
)
Code
$data = "Microsoft,https://microsoft.com
Stackoverflow,https://stackoverflow.com";
$result = array();
foreach(explode(' ', $data) as $values){
$key_value = explode(",", $values);
if (isset($key_value[0]) && isset($key_value[1]))
$result[$key_value[0]] = $key_value[1]; // Construct array with meaningful key
}
var_dump($result);
Result
array(2) { ["Microsoft"]=> string(21) "https://microsoft.com" [" Stackoverflow"]=> string(25) "https://stackoverflow.com" }

Combine 2 or more JSON in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My current JSON value is like this:
{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"]}{"grade":["XXL","A","B","S"]}{"packages":["Carton Boxes","Baskets"]}
But I would like to want the output to be like this:
{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"],"grade":["XXL","A","B","S"],"packages":["Carton Boxes","Baskets"]}
JSON is just a text representation of some data structure. Restore the data structure from the JSON strings, use PHP to modify it (or create a new data structure if it's more appropriate), encode the updated/new data structure to JSON again.
It seems the "JSON" you posted as input is not a JSON at all. It is the concatenation of three JSON strings. It doesn't work this way!
// Input JSON strings
$json1 = '{"vegetable_names":["vegetables 1","vegetables 2","vegetables 3"]}';
$json2 = '{"grade":["XXL","A","B","S"]}';
$json3 = '{"packages":["Carton Boxes","Baskets"]}';
// Restore the data structures as arrays
$data1 = json_decode($json1, TRUE);
$data2 = json_decode($json2, TRUE);
$data3 = json_decode($json3, TRUE);
// Combine them; it seems all you need is a simple merging
$data = array_merge($data1, $data2, $data3);
// Encode the combined arrays as JSON again
$output = json_encode($data);
I guess you get the Json like you described. If not I suggest you follow Paul Crovella's solution in making it right from the start.
So presumed that is no option for you, how about decoding the Json to an object or array merging those two or more and then encode them again as Json.
Ugly , but if the Json is created by a source independent from you, you can do it like that.

How to acces the second value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was wondering if you could give two values ​​to a class and then acces to the second one by POST, something like this (part of the code):
echo "<select name='selecttsk' id='selecttsk'>";
while($w = $bd->obtener_fila($tasker, 0)){
echo "<option class='opcion1' value ='".$w[1]/$w[2]."'>".$w[0]."</option>";
}
echo "</select>";
?>
and then i need to do something like this in other file
$var = $_POST[selecttsk];
but i need $w[2]
thanks
I suppose your $_POST['selecttsk'] does have the values in the following format:
"foo/bar"
You could use "explode" in PHP to get the second part (bar), for example:
$postvar = $_POST['selecttsk'];
$vars = explode("/", $postvar);
// Then
$var = $vars[1]; // Will be the $w[2] from the form
Look into: http://php.net/explode
Beware that if $w[1] or $w[2] ever contains a "/" you might get unexpected results, you could use the limit function of explode to mitigate that issue.
However - I would generally not recommend this workflow.
Why do you need to send two variables with one select?
(could you show us som example of what $w contains)

Appending to an array without copying [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Generally we add to an array with
$myarray[] = $myItem
but if $myItem is a massive object I don't want it to get copied, instead I want it to be assigned by reference. Something like
$myarray[] = &$myItem
but that doesn't work and instead replaces every element in $myarray with $myItem
I tried
$myarray[count($myarray)] = &$myItem
but it still replaces everything in $myarray
I am running PHP v5.5
Objects are always assigned by reference. So:
$collection = array();
$blah = new Blah();
$blah->param = "something";
$collection[] = $blah;
$blah->param = "changed";
echo $collection[0]->param; // will output "changed"
According to How to push a copy of an object into array in PHP
Objects are always passed by reference in php 5 or later.
Therefore this question isn't really a concern anymore.

php: when need to use unset() function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<?php
$str = 'Hello world!';
echo $str;
unset($str);
?>
Question:
When do I need to use unset()? For the above script, I think that is not necessary to use it. So I just wonder in what situation need to use it?
i mostly use it when deleting sessions...
unset($_SESSION['user']);
Lets say you have an array:
$test = array(
'one' => 1,
'two' => 2,
'three' => 3
);
if you don't need three anymore easily you can do unset($test['three']); if you don't have unset, how would you do it?
Try this code
<?php
$str = 'Hello world!';
$myvar = 'another var';
$params = array($str,$myvar);
myunset($params);
function myunset($params){
foreach($params as $v){
unset($GLOBALS[$v]);
}
}
var_dump($myvar); //NULL
?>
This is a question about PHP garbage collection, first we need to know that:
PHP performs garbage collection at three primary junctures:
When you tell it to
When you leave a function
When the script ends
http://www.tuxradar.com/practicalphp/18/1/10
You can follow the link above to get more information, my suggestion is that you can use unset when processing a big resource.
Unset function actually use for unset the value of any variable you can do this
unset($var);
unset($_SESSION['logout']);
unset($row['firstname']);

Categories