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 を使用する場合、私が何をする必要があるか、または簡単な解決策について何か提案はありますか? 爆発を使用して for each ループを実行しようとしましたが、実行する必要がある方法から離れているか、何かが不足しています。以下の結果に沿って、さらに何かを得ています。

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

怠惰なオプションは、usingparse_strに変換,した後に&使用し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 に答える