简体   繁体   English

如何将包含数组值的字符串转换为PHP数组?

[英]How to convert a string containing an array value to a PHP array?

I have a string that contains an array like: 我有一个包含如下数组的字符串:

$tarray = Array ( [gt_ref_id] => 36493115 [tender_notice_type] => [organisation_name] => ROSALES WATER DISTRICT [address] => No. 5 Bonifacio Street [address2] => [contact_person] => [tender_notice_no] => ROSALWD 2016-011-0144(Ref: 4206661)
)

but I want to access the value of this array like: 但我想像这样访问此数组的值:

echo "ref id = ".$tarray['gt_ref_id'];

It should output like: 它应该输出如下:

ref id = 36493115

but I can't because it's a string. 但我不能,因为它是一个字符串。 I could if it was an array. 我可以,如果它是一个数组。

How can I convert the string to a proper PHP array? 如何将字符串转换为适当的PHP数组?

If you want store a php array on you database you can try with json_encode or serialize , and when you would need retrive data from you database, you can use json_decode or unserialize . 如果要在数据库上存储一个php数组,可以尝试使用json_encodeserialize ,当需要从数据库中检索数据时,可以使用json_decodeunserialize

Using JSON 使用JSON

Examples(store as json): 示例(存储为json):

$myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24);
$toStore = json_encode($myArray); // return a string: {"name":"Jack","lastname":"Smith","0":24}

mysqli_query($link,
    'INSERT INTO myTable (data)
    VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);

Examples(retrieved from json): 示例(从json中检索):

$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = json_decode($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)

Using serialize 使用serialize

Example(store serialized): $myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24); 示例(商店序列化):$ myArray = array('name'=>'Jack','lastname'=>'Smith',24); $toStore = serialize($myArray); $ toStore = serialize($ myArray); // return a string: a:3:{s:4:"name";s:4:"Jack";s:8:"lastname";s:5:"Smith";i:0;i:24;} //返回一个字符串:a:3:{s:4:“ name”; s:4:“ Jack”; s:8:“ lastname”; s:5:“ Smith”; i:0; i:24 ;}

mysqli_query($link,
    'INSERT INTO myTable (data)
    VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);

Examples(retrieve serialized): 示例(检索序列化):

$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = unserialize($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)

After : 之后:

if you need access to you data from converted array, you can call like: 如果您需要从转换后的数组访问数据,则可以这样调用:

$row['name'] // return "Jack"

Another ways 另一种方式

Regexp: 正则表达式:

You can try use regexp, but this not the best way because sometime is too slow to process data, and maybe, if you don't know security aspects, this definitely not is the best way. 您可以尝试使用regexp,但这不是最好的方法,因为有时处理数据的速度太慢,而且也许,如果您不了解安全方面,那么绝对不是最佳方法。

Tokenizer: 分词器:

You can try create you own token processor, like template engine, but this is the most large way... 您可以尝试创建自己的令牌处理器,例如模板引擎,但这是最大的方法...

Learn more about the functions: 了解有关功能的更多信息:

Pros: 优点:

  1. Support multiple data-types: multidimentional array , object , integer , float , string , and many more data except resource . 支持多种数据类型:多维arrayobjectintegerfloatstring以及除resource以外的更多数据。
  2. Native support for serialize and unserialize since PHP4. 自PHP4以来,本机支持serialize和反unserialize
  3. Native support for json_encode and json_decode since PHP 5.2.0 自PHP 5.2.0起对json_encodejson_decode机支持
  4. Fast and secure encode and decode. 快速,安全的编码和解码。

As suggested by Olaf Erlandsen you should probably store your array in another format -- serialized or as a json dump. 根据Olaf Erlandsen的建议,您可能应该以其他格式存储数组-序列化或json转储。 I'd prefer the latter. 我希望后者。

However, chances are that you're not the one generating this (rather odd) string. 但是,很有可能您不是生成此(相当奇怪)字符串的人。 It may be provided by someone else. 它可能由其他人提供。 In that case you could use a regular expression (RegEx) to extract the keys and values of the array. 在这种情况下,您可以使用正则表达式(RegEx)提取数组的键和值。

You can use preg_match_all() to match them and then loop over the matches to join them into an array. 您可以使用preg_match_all()来匹配它们,然后循环匹配以将它们加入数组。 I find it easier to loop over the results when the PREG_SET_ORDER flag is set. 我发现设置PREG_SET_ORDER标志时更容易遍历结果。

Example code: 示例代码:

$string = "Array ( [gt_ref_id] => 36493115 [tender_notice_type] => hiha [organisation_name] => ROSALES WATER DISTRICT [address] => No. 5 Bonifacio Street [address2] => [contact_person] => [tender_notice_no] => ROSALWD 2016-011-0144(Ref: 4206661))";
$string = substr( $string, 8 ); # Strip Array ( , from beginning of string.
$string = substr( $string, 0, - 1 ); # Strip last ) from string.

preg_match_all( "/\[(.*?)\] => ([^\[]*)/", $string, $matches, PREG_SET_ORDER );

foreach ( $matches as $match ) {
    $tarray[ $match[1] ] = substr( $match[2], 0, - 1 );
    # Note that $match[2] contains a trailing white-space, stripping it with substr().
    # On another note, you should probably check whether $match[2] has any content.
}

var_dump($tarray);

I put the pattern up on regex101, that'll probably make things clearer if you're new to these patterns . 我将这种模式放在regex101上,如果您不熟悉这些模式 ,那可能会使事情变得更清楚。

Note: I'm not exactly a RegEx-genious, maybe someone can check the pattern I provided. 注意:我并不是RegEx专家,也许有人可以检查我提供的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM