user1072014
user1072014

Reputation: 37

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?

my string:

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

I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.

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

First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.

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

Upvotes: 1

Views: 160

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270617

You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.

$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"
}

Upvotes: 4

mario
mario

Reputation: 145482

The lazy option would be using parse_str after converting , into & using strtr:

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

I would totally use a regex here however, to assert the structure a bit more:

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

Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)

Upvotes: 3

Mark Baker
Mark Baker

Reputation: 212412

$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);

Upvotes: 2

Related Questions