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.
Related
I would like to output a JSON string with an optional fields.
Right now I do it as simple as:
echo json_encode(array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
));
Now, say, I would like to include/exclude the 'asd' element based on some logic (using an inline if or some function or something else).
I have no idea how to do it, because, AFAIK, there is no such type in PHP that can force json_encode to skip this field - everything returns null or empty fields but does not skip the field itself.
Any ideas someone?
do you mean something like this:
$arr = array(
array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
),
array(
'qwe' => 4,
'asd' => '',
'zxc' => 6
)
);
foreach ($arr as $key => $row) {
if ($row['asd'] == '') {
unset($arr[$key]['asd']);
}
}
echo json_encode($arr);
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;
?>
$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
I have a form that will need to except input from users to filter the search results. I am not the original designer of the form. I one of two ways that I saw to filter the results. A) I could have tried to restrict the sql query to the selected codes or B) filter the results that are returned. I am trying B.
I have tried
var_dump(array_intersect_key($array1, $array2));
No success:
Array1 looks like this:
array (
'|00006|5' => array('pid' => 111
'provider_id' => 123456 )
'|93000|34' => array('pid' => 112
'provider_id' => 127654 )
'|93225|1' => array('pid' => 113
'provider_id' => 127893 )
)
I figured out how the pipes got into the key values and I tried to adjust my keys to match but that did not work either.
Any suggestions on how I can filter these types of results with a key that is not a single value and is dynamically changed?
Array2 look like:
99232 => string '99232' (length=5)
85610 => string '85610' (length=5)
93970 => string '93970' (length=5)
93000 => string '93000' (length=5)
99406 => string '99406' (length=5)
99215 => string '99215' (length=5)
I made the key value and the string value the same trying to setup some type of filtering.
But since the third value in array1 will be dynamically delivered in a while clause. I have no way of matching that number to the Array2.
My expected outcome is
array (
'|93000|34' => array('pid' => 112
'provider_id' => 127654 )
)
As that only one of the 6 inputs matched one of the array1 values.
You have to define your key comparison function and then use array_intersect_ukey():
$a = array (
'|00006|5' => array('pid' => 111,
'provider_id' => 123456 ),
'|93000|34' => array('pid' => 112,
'provider_id' => 127654 ),
'|93225|1' => array('pid' => 113,
'provider_id' => 127893 ),
);
$b = array('93000' => '93000');
print_r(array_intersect_ukey($a, $b, function($ka, $kb) {
if ($ka[0] == '|') { // transform key
$ka = substr($ka, 1, strrpos($ka, '|') - 1);
}
if ($kb[0] == '|') { // transform key
$kb = substr($kb, 1, strrpos($kb, '|') - 1);
}
// perform regular comparison
return strcmp($ka, $kb);
}));
or you can do this.
good luck :)
$parsed1 = array();
foreach($array1 as $key => $value) {
$splited = explode("|", $key);
$parsed1[$splited[1]] = $value;
}
var_dump(array_intersect_key($parsed1,$array2));
I have this issue i am writing a array to a file but when i unset() some sub arrays it keeps the comma or when i add anther sub array to the end it add a comma.
eg:
$account_data = include('./*****/AccountData.php');
$account_data[$username]['Name'] = $name;
$account_data[$username]['Password'] = $password;
$account_data[$username]['RandID'] = $randid;
$account_data[$username]['PublicD'] = $publicdownload;
$account_data[$username]['Enabled'] = $enabled;
$account_data[$username]['Admin'] = $admin;
$configdata = "<?php\n\nreturn ".var_export($account_data, true)."; \n\n?>";
$file = fopen('./*****/AccountDataTest.php', 'w');
fwrite($file, $configdata);
fclose($file);
when i run that code to add a sun array i get this
<?php
return array (
'Ryan' => array (
'Name' => 'Ryan',
'Password' => '',
'RandID' => '',
'PublicD' => 0,
'Enabled' => 1,
'Admin' => 0,
),
'Chris' => array (
'Name' => 'Christopher',
'Password' => '',
'RandID' => '',
'PublicD' => 1,
'Enabled' => 1,
'Admin' => 1,
),
);
?>
as you can see it adds a comma and when i run my unset function the code for the AccountData.php file will look the same with out the Chris but it has the following comma at the end of Ryan.
I am not sure how I can fix this I have been googling with not much luck.
I'm not sure if I understand the problem, but you would probably save yourself a lot of headaches by using serialize and unserialize to save your data in a file.
I'm not entirely sure why you would want to do this, but store the data in a variable first and run it through a simple regex to remove the extra comma at the very end and after 'Admin' => *
Regex Tutorial: http://weblogtoolscollection.com/regex/regex.php