Hope everything is good.
I use php file() and it works very well. I only need to separate my "values" in the txt-file with a new row, and then 'file()' will give me the contents of the txt-file as an array with all the values separately.
I do not know if I can take the same function one step further to achieve 'key/values' and 'multidimensional arrays'. If not, what do I have for other options to be able to save 'text data' in a txt file and then get it back in a multidimensional array?
At the moment, I only get the following:
[0] => 'value1',
[1] => 'value2',
[2] => 'value3',
If you know any solutions that are very straightforward and can put me on the right track here, I am very grateful.
A simple primer for doing this with JSON:
// example array of data
$myarray = array();
$myarray[] = ['name' => 'value 1','age' => '31','city' => 'nowhere'];
$myarray[] = ['name' => 'value 2','age' => '12','city' => 'somewhere'];
$myarray[] = ['name' => 'value 3','age' => '67','city' => 'anywhere'];
print_r($myarray);
// to save your array to a file
file_put_contents('/path/to/file.json',json_encode($myarray));
// now to retrieve:
$myarray = json_decode(file_get_contents('/path/to/file.json'),true);
print_r($myarray);
By doing it this way, you retain those keys you want, and the values. The JSON encoding/decoding handles all the painful bits of storing it as text in a flatfile.
Related
How do I save the string below with the variables to a array? It doesnt seem to work..
$str[] = {'name':'$data['name']','y':$data['values'],'key':'$data['key']'},
$str_str = implode(' ', $str);
echo $str_str;
Thanks.
You should read about basic array and string handling in PHP. Something like this should work:
$str[] = [
'name' => $data['name'],
'y' => $data['values'],
'key' => $data['key']
];
Maybe the best way is just use $str[] = json_encode($data);
Are you trying to save a JSON string into an array?
$var[] saves a value to the first available numeric key in the array $var
The string you would like to save looks like a JSON string, if that's what you want you can do so by:
$var[] = json_encode($data)
If the data array contains the following:
Array
(
[name] => value name
[y] => value y
[key] => value key
)
JSON encoding this array will give you:
{"name":"value name","y":"value y","key":"value key"}
I have a simple session array and I'm pushing page titles in it, as strings:
$_SESSION['sesArray'][] = $pageTitle;
and another predefined associative array with page titles and links:
$assoc=array(array('title' => 'page title', 'link' => 'page link'));
The session array gets flooded with titles so I'm taking out duplicates:
$array1 = array_unique($_SESSION['sesArray']);
My question is: how can I compare the $assoc array against $array1 to check for page titles that exist in both and eliminate them, ending up with another array that contains unique titles along with the link?
I have tried using:
$result= array_diff_key($assoc, $array1 );
But some duplicate titles are indeed removed and some are not.
Any ideas?
ETA data:
$array1= array('Museum', 'Club');
$assoc= array(array('title' => 'Museum', 'link' => 'museum.php' ),
array('title' => 'club', 'link' => 'club.php'));
You are not really doing a diff because an array of arrays is by definition going to have nothing in common with an array of scalars. What you need to do is filter $assoc based on the contents of $array1. Try this:
$array1= array('Museum','Club');
$assoc= array(array('title' => 'Museum', 'link' => 'museum.php' ),
array('title' => 'club', 'link' => 'club.php'));
$fn = function($arr) use ($array1) {
return !in_array($arr['title'], $array1);
};
$result =array_filter($assoc, $fn);
Ah, the infamous tech-interview problem ("compare 2 arrays and to find common entries").
try something along the lines of:
$ass = array_keys($assoc);
foreach($ass as $a)
{
while (isset($_SESSION['sesArray'][$a]))
{
unset($_SESSION['sesArray'][$a]);
}
}
The way PHP associates its tuple arrays allows you to avoid the ugly O(n^2) complexity of this issue.
I have a multidimensional array or arrays which I also use in my configuration file. The file is also manually edited so I want some of the keys to have fixed position. The code reads configuration file with this array, modifies, insert keys etc and then saves it back. On save I sort the keys but now I found that it is not good enough.
Is there any way to have
the key 'full_name' always as the first key
the key 'version' as second one
and the rest of the keys to be sorted alphabetically?
Sample of the array....
array (
'skroob' =>
array (
'ssh' => 'skroob',
'codebase_path' => '/srv/www/htdocs/imacs/radek/4.0.1',
'ssh_status' => 'ok',
'version' => '4.0.1',
'ssh_last_access' => '2012-Feb-17 10:07:26',
'edu_url' => 'https://testing/imacs/radek/4.0.1',
'full_name' => 'skroob 4.0.1',
),
'testing' =>
array (
'full_name' => 'My beautiful testing server (trunk)',
'version' => 'trunk',
'ssh' => 'testing',
'codebase_path' => '/srv/www/htdocs/imacs/radek/trunk',
'ssh_last_access' => '2012-Feb-17 10:07:26',
'ssh_status' => 'ok',
),
)
Here's one way. It sorts the array alphabetically, by key. Then it reverses the array and unsets the full_name and version keys. Then it adds those keys again, so they get placed at the end of the array. Lastly, it reverses the array again. Kinda hacky but I'm not sure there's a much better way to do what you're asking.
ksort($arr['skroob']);
$arr['skroob'] = array_reverse($arr['skroob']);
$version = $arr['skroob']['version'];
$full_name = $arr['skroob']['full_name'];
unset($arr['skroob']['full_name'], $arr['skroob']['version']);
$arr['skroob']['version'] = $version;
$arr['skroob']['full_name'] = $full_name;
$arr['skroob'] = array_reverse($arr['skroob']);
Another solution is to use uksort and write a small callback function. That would probably look a bit more professional.
I have a weird problem here. I'm using an associative array in php (using cakePHP) which has the following form:
$my_array = array(
'data['a']['b'] => 'value1',
'data['b']['c'] => 'value2',
'data['b']['d'] => 'value3',
'data['e'] => array(
'data['e1']['e2']' => 'value3',
'data['e1']['e3']' => 'value4'));
The problem I'm having is that
'data['e1']['e2']' => 'value3' and 'data['e1']['e3']' => 'value4'
are taken like an array like this:
'data['e1']' => array(
['e2'] => 'value3',
['e3'] => 'value4');
I don't want these to be taken as arrays, I want them to be taken as key and value of the array 'data['e']'. As a matter of fact, I want all the elements of the arrays $my_array and 'data['e']' to be taken as keys and values of the corresponding array (not as arrays).
Any help please?
P.S This seems to happen only when I do a debug on cakePHP, if I don't use cakePHP everything seems to be fine and "data" comes from a cURL posted data to cakePHP
Your code is invalid PHP. My best guess is that it should look like this:
$my_array = array(
$data['a']['b'] => 'value1',
$data['b']['c'] => 'value2',
$data['b']['d'] => 'value3',
$data['e'] => array(
$data['e1']['e2'] => 'value3',
$data['e1']['e3'] => 'value4'));
Please show us the contents (for instance, using print_r) of $data.
POSTed data in a certain syntax is automatically parsed into $_POST as array. If you want to get the raw input, use file_get_contents('php://input'). See http://php.net/manual/en/wrappers.php.php.
I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);
var_export()
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.