how to serilaze and unserialize an array in php - php

I have an array like this:
$arr = array(
'type' => 'airport ',
'airport' => 'Delhi Indra Gandhi',
'address' => '',
'city' => '',
'postcode' => ''
);
I serialized it and saved it wp database.
$wpdb->insert( 'table_name', serialize($arr), '%s' );
When I am selecting this data in front end it giving me string like this
a:5:{s:4:\"type\";s:7:\"airport\";s:7:\"airport\";s:18:\"Delhi Indra
Gandhi\";s:7:\"address\";s:0:\"\";s:4:\"city\";s:0:\"\";s:8:\"postcode\";s:0:\"\";}
When I am unserializing it , it gives nothing means an empty string.
Kindly help me.

When you unserialize use urldecode and unserialize example:
$str = serialize($arr);
$strenc = urlencode($str);
Unserialize:
$array = unserialize(urldecode($strenc));

Related

Getting a value from associative arrays PHP

I have an array..
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
)
and I am trying to extract the name using
$fileName = $file['meta'['name'];
which gives me a Illegal string offset 'name' error.
The value of $file['meta'] is a string, not an array. That means your approach to access the value does not work.
It looks like that meta value string is a json encoded object. If so you can decode it and then access the property "name" of the resulting object.
Take a look at this example:
<?php
$file = [
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => []
];
$fileMeta = json_decode($file['meta']);
var_dump($fileMeta->name);
The output obviously is:
string(12) "IMAG0161.jpg"
In newer version of PHP you can simplify this: you do not have to store the decoded object in an explicit variable but can directly access the property:
json_decode($file['meta'])->name
The output of this obviously is the same as above.
This is happening because your meta is a json, so you should decode and then access whatever you need, not that I placed true as second parameter becuase i wanted to decode as an associative array instead of an object
$decoded = json_decode($file['meta'],true);
echo $decoded['name'];
//print IMAG0161.jpg
You can check a live demo here
But you can easily access as an obect
$decoded = json_decode($file['meta']);
echo $decoded->name;
//print IMAG0161.jpg
You can check a live demo here
<?php
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
);
$meta=$file['meta'];
$json=json_decode($meta);
echo $json->name;
?>

PHP string convert to array

$paypal_details = "array (
'last_name' => 'Savani',
'item_name' => 'Description and pricing details here.',
'item_number' => '101',
'custom' => 'localhost',
'period' => '1',
'amount' => '10.01'
)";
Here is sample string in which contain full array.
Is this possible to convert string to array as it is?
You really should try to get the information in JSON or XML format instead, which both can be parsed natively by PHP. If that is not possible you can use the code snippet below to get a PHP array from the string. It uses regular expressions to turn the string into JSON format and then parses it using json_decode.
Improvements should of course be made to handle escaped single quotes within values etc., but it is a start.
$paypal_details = "array (
'last_name' => 'Savani',
'item_name' => 'Description and pricing details here.',
'item_number' => '101',
'custom' => 'localhost',
'period' => '1',
'amount' => '10.01'
)";
# Transform into JSON and parse into array
$array = json_decode(
preg_replace(
"/^\s*'(.*)' => '(.*)'/m", # Turn 'foo' => 'bar'
'"$1": "$2"', # into "foo": "bar"
preg_replace(
"/array \((.*)\)/s", # Turn array (...)
'{$1}', # into { ... }
$paypal_details
)
),
true
);
echo "Last name: " . $array["last_name"] . PHP_EOL;
Output:
Last name: Savani
You can use the explode() function.
<?php
$str = "Hello world. It's a beautiful day.";
print_r(explode(" ", $str));
http://www.w3schools.com/php/func_string_explode.asp

String to array conversion if string has content like an array

I have something like this:
array('fields' => array(
0 => array('name' => 'family_name',
'label' => 'Family Names'),
array('name' => given_names',
'label' => 'Given Names'),
array('name' => 'additional_names',
'label' => 'Additional Names'),
array('name' => 'honorific_prefixes',
'label' => 'Honorific Prefixes'),
array('name' => honorific_suffixes',
'label' => 'Honorific Suffixes')
)
)
in a variable as string. The whole thing is in one database field. If I output the variable, it is a string.
I would have an array with the content as subarrays. How do I convert this value into an array?
I searched with google, but I found explode and split and so on, but I think I miss the key word to find any solution.
Thank you for any help in this case.
Try using eval(), https://secure.php.net/manual/en/function.eval.php
eval("\$array = $string;");
print_r($array);
Your string is not built correctly to put it into the eval function. Two strings inside don't have the preceding quote and that will lead to a parse error. But you can correct it with:
$string = str_replace("=> given_names'", "=> 'given_names'", $string);
$string = str_replace("=> honorific_suffixes'", "=> 'honorific_suffixes'", $string);
After that you can use the answer of shapeshifter (please mark his answer as the correct one):
eval("\$array = $string;");
var_dump($array);
If you just look for a method to save and restore your arrays you could also use serialize / unserialize.

Convert a string into array PHP

Sometime back I was getting alot of data via some API and I saved it into a flat file doing a simple var_dump or print_r. Now I am looking to process the data and each line looks like:
" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y',
'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name'
=> 'MNOP', 'email' => 'abc#example.com', 'city' => 'London',
'street_address' => 'Sample', 'first_name' => 'Sparsh',"
Now I need to get this data back into an array format. Is there a way I can do that?
What about first exploding the string with the explode() function, using ', ' as a separator :
$str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
$items = explode(', ', $str);
var_dump($items);
Which would get you an array looking like this :
array
0 => string ''middle_initial' => ''' (length=22)
1 => string ''sid' => '1419843'' (length=18)
2 => string ''fixed' => 'Y'' (length=14)
3 => string ''cart_weight' => '0'' (length=20)
...
And, then, iterate over that list, matching for each item each side of the =>, and using the first side of => as the key of your resulting data, and the second as the value :
$result = array();
foreach ($items as $item) {
if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
$result[ $matches[1] ] = $matches[2];
}
}
var_dump($result);
Which would get you :
array
'middle_initial' => string '' (length=0)
'sid' => string '1419843' (length=7)
'fixed' => string 'Y' (length=1)
'cart_weight' => string '0' (length=1)
...
But, seriously, you should not store data in such an awful format : print_r() is made to display data, for debugging purposes -- not to store it an re-load it later !
If you want to store data to a text file, use serialize() or json_encode(), which can both be restored using unserialize() or json_decode(), respectively.
Although I wholeheartedly agree with Pascal Martin, if you have this kind of data to deal with, the following (as Pascal's first suggestion mentions) could work depending on your actual content. However, do yourself a favor and store your data in a format that can be reliably put back into a PHP array (serialize, JSON, CSV, etc...).
<pre>
<?php
$str = "\" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',\"";
function myStringToArray($str) {
$str = substr($str, 1, strlen(substr($str, 0, strlen($str)-2)));
$str = str_replace("'",'',$str);
$strs = explode(',', $str);
$arr = array();
$c_strs = count($strs);
for ($i = 0; $i < $c_strs; $i++) {
if (strpos($strs[$i],'=>') !== false) {
$_arr = explode('=>',$strs[$i]);
$arr[trim($_arr[0])] = trim($_arr[1]);
}
}
return $arr;
}
print_r(myStringToArray($str));
?>
</pre>
http://jfcoder.com/test/substr.php
Note, you would need to adjust the function if you have comma's within your array member's content (for instance, using Pascal's suggestion about the ', ' token).
It would be better and much easier to work with Serialize and Unserialize instead of var_dump.
in that form, maybe you could try a
explode(' => ', $string)
and then go through the array and put the pairs together in a new array.
As long as it's the output of print_r and an array, you can use my little print_r converter, PHP source code is available with the link.
The tokenizer is based on regular expressions so you can adopt it to your needs. The parser deals with forming the PHP array value.
You will find the latest version linked on my profile page.

How to convert this string into an array

I have a string being returned from my database that I want to use as an array. It is already in an assoc array form. Here is a sample of what this looks like so far. How would I do this?
'test1' => 'value 1',
'test1' => 'value 1a,
'test2' => 'value 2'
Ok, this is the database code:
SELECT
inventory.invId,
GROUP_CONCAT(CONCAT( '''', inventory.vehicle, ''' => ', '''', inventory.color, '''' )) AS vehicle,
vehicle.vehicle_id
FROM
inventory
Inner Join vehicle ON vehicle.invId = inventory.invId
This is the print_r from the database results
Array
(
[0] => Array
(
[system] => AR3
[vehicle] => 'geo' => 'red', 'honda' => 'blue', 'ford' => 'black'
[vehicle_id] => 1232132
)
)
I'd strongly advise against returning data in such a format. First of all, you need to take much more care creating this special format to make it parse-able. What if a value contains the character "'"? You'd get 'key' => 'value '', which will throw the whole parsing process for a loop. Secondly, it's a non-trivial form to parse and would require a lexer or using the PHP tokenizer, which is much more work than it's worth.
For transporting native structures in strings, there's a special serialized format. You're just reinventing the wheel here. Badly, I might add. :)
Just return the results as normal SELECT * FROM table … and build the array in PHP, that's the proven and fastest way to do it.
$f = array();
$a1 = explode( ',', $string );
foreach( $a1 as $s ) {
$a2 = explode( '=>', $s ) {
$a2[0] = preg_replace( "/^'/", '', $a2[0] );
$a2[0] = preg_replace( "/'\s*$/", '', $a2[0] );
$a2[1] = preg_replace( "/^\s*'/", '', $a2[1] );
$a2[1] = preg_replace( "/'$/", '', $a2[1] );
$f[$a2[0]] = $a2[1];
}
}
note: Thanks for adding the code block formatting codaddict! ... Ps agree with answer on how to return result better: this is just a literal answer to Q

Categories