开发者

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'开发者_如何学Go => '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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜