PHP string convert to array - php

$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

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 Striping/Exporting single strings from an array

I have an array, like this:
)array (
'date' => '2015-12-10T00:16:58+0000',
'from' =>
array (
'name' => 'Joe Bloggs',
'user_id' => 3220562,
),
'message' => ':ip=1.1.1.1',
)
And here's my code:
$string = var_export($h, true);
echo $string;
And finally, here's what I would like to achieve:
I would like to export single strings from the array (for example I want to export 'message', and then I would get an output of ":ip=1.1.1.1").
I have tried things like $h['message'] and this doesn't work, so I'm just wondering what's the easiest / cleanest way to do this.
Any help would be greatly appreciated.

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.

how to serilaze and unserialize an array in 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));

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.

Categories