just trying to add some setting for the admin in a database entry.
i've saved;
array('aviva'=>'aviva','teacher'=>'teacher');
into the field 'fullPara' but can't seem to get it back into an array? Just spits it out as a string and i've tried eval but not sure where to go from here?
echo $userTypes['fullPara']; // spits out array('aviva'=>'aviva','teacher'=>'teacher');
any pointers welcome!
best, Dan
You want to look into the serialize() and unserialize() functions PHP offers.
Here is an example:
$array = array('1', '3', '4');
$s_array = serialize($array);
// insert that into the db.
// later on when fetching.
$array = unserialize($array_from_db);
print_r($array); // viola
EDIT
I do NOT recommend this but here is how you would convert it to an array using eval:
eval("\$array = " . $data_from_Db);
print_r($array);
Should get you what you were after.
If you already have a string of "array('aviva'=>'aviva','teacher'=>'teacher'); " and you wish to turn it into an array, this should work...
$str = "array('aviva'=>'aviva','teacher'=>'teacher');";
eval("\$foo = $str");
var_dump($foo);
It's really not the best way of doing it though.
Related
This is the data that i need to extract like example profile_contact_numbers
so the output will be +639466276715
how can i do it in php code??
any help will do regards
a:2:
{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}
I'm not sure 100% this can go into an array but try the unserialize function
$json_resp = {your values};
$array[] = unserialize($json_resp);
To check if it has gone into an array print_r on $array.
Read this link if the code above doesn't work
http://php.net/manual/en/function.unserialize.php
I have managed to fix it
$serialized = array(unserialize('a:2:{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}'));
var_dump($serialized);
use code :
$var = preg_split('["]','{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}');
echo $var[1].'='.$var[3]; // profile_contact_numbers=+639466276715
echo $var[5].'='.$var[7]; // profile_position=Courier
I just want to quickly store an array which I get from a remote API, so that i can mess around with it on a local host.
So:
I currently have an array.
I want to people to use the array without having to get it from the API.
There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc
Is there a function like store_array() or restore_arrray() ?!
The best way to do this is JSON serializing. It is human readable and you'll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions
json_encode
json_decode
Example code:
$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true
You can write your own store_array and restore_array functions easily with this example.
For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).
If you don't need the dump file to be human-readable, you can just serialize() the array.
storing:
file_put_contents('yourfile.bin', serialize($array));
retrieving:
$array = unserialize(file_get_contents('yourfile.bin'));
Use serialize and unserialize
// storing
$file = '/tmp/out.data';
file_put_contents($file, serialize($mydata)); // $mydata is the response from your remote API
// retreiving
$var = unserialize(file_get_contents($file));
Or another, hacky way:
var_export() does exactly what you want, it will take any kind of variable, and store it in a representation that the PHP parser can read back. You can combine it with file_put_contents to store it on disk, and use file_get_contents and eval to read it back.
// storing
$file = '/tmp/out.php';
file_put_contents($file, var_export($var, true));
// retrieving
eval('$myvar = ' . file_get_contents($file) . ';');
Another fast way not mentioned here:
That way add header with <?php start tag, name of variable \$my_array = with escaped \$ and footer ?> end tag.
Now can use include() like any other valid php script.
<?php
// storing
$file = '/tmp/out.php';
$var = ['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5];
file_put_contents($file,
"<?php\n\$my_array = "
.var_export($var, true)
.";\n?>"
);
// retrieving as included script
include($file);
//testing
print_r($my_array);
?>
out.php will look like this
<?php
$my_array = array (
'a'=>1,
'b'=>2,
'c'=>3,
'd'=>4,
'e'=>5
);
?>
You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure.
I'd suggest using a language independent structure though, such as JSON. This will allow you to load the files using different languages than PHP, in case there's a chance of that later. json_encode to store it and json_decode($str, true) to return it.
Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with:
file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');
and call normally with
include "dic.php";
Use php's serialze:
file_put_contents("myFile",serialize($myArray));
I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
In your specific case:
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
//writing the array to file
$dx->write('myarray', $array1);
//reading array from file
$array2 = $dx->read('myarray')
//modifying array in file after making changes
$dx->write('myarray', $array2);
I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.
I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));
I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one