1

我是新的 PHP 问题,我正在尝试从我拥有的以下数据字符串创建一个数组。我还没有得到任何工作。有没有人有什么建议?

我的字符串:

Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35

我想动态创建一个名为“My_Data”的数组并让 id 显示类似于我的以下内容,请记住我的数组可能会在不同时间返回或多或少的数据。

My_Data
(
    [Acct_Status] => active
    [signup_date] => 2010-12-27
    [acct_type] => GOLD
    [profile_range] => 31-35
)

第一次使用 PHP,有人对我需要做什么或有一个简单的解决方案有任何建议吗?我试过使用爆炸,为每个循环做一个,但要么我在我需要做的路上走得很远,要么我错过了一些东西。我得到了更多符合以下结果的内容。

Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} ) 
4

3 回答 3

4

您需要explode()打开字符串,,然后在foreach循环中,explode()再次打开=并将每个字符串分配给输出数组。

$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
  // Loop over them
foreach ($outer as $inner) {
  // And split each of the key/value on the =
  // I'm partial to doing multi-assignment with list() in situations like this
  // but you could also assign this to an array and access as $arr[0], $arr[1]
  // for the key/value respectively.
  list($key, $value) = explode("=", $inner);
  // Then assign it to the $output by $key
  $output[$key] = $value;
}

var_dump($output);
array(4) {
  ["Acct_Status"]=>
  string(6) "active"
  ["signup_date"]=>
  string(10) "2010-12-27"
  ["acct_type"]=>
  string(4) "GOLD"
  ["profile_range"]=>
  string(5) "31-35"
}
于 2012-11-08T00:44:45.180 回答
3

parse_str转换,&using后,将使用惰性选项strtr

$str = strtr($str, ",", "&");
parse_str($str, $array);

但是,我会在这里完全使用正则表达式来更多地断言结构:

preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);

这将跳过任何不是由字母、数字或连字符组成的属性。(当然,问题是这是否是您输入的可行约束。)

于 2012-11-08T00:45:42.387 回答
2
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);
于 2012-11-08T00:45:13.773 回答