Jump to content

convert string to array *** SOLVED ***


poe

Recommended Posts

i have a string like this:

[pre]
$mystring = "[name][age][pet][mike][22][dog][john][25][cat][kim][26][bird][pam][18][fish]";
[/pre]

each item is surrounded by []

i want to strip the [] and create into an array with the first 3 as the keys, then every other third grouping the values.

ie

$people[1] = array( 'name'=>'mike', 'age'=>'22', 'pet'=>'dog');
$people[2] = array( 'name'=>'john', 'age'=>'25', 'pet'=>'cat');
$people[3] = array( 'name'=>'kim', 'age'=>'26', 'pet'=>'bird');
$people[4] = array( 'name'=>'pam', 'age'=>'18', 'pet'=>'fish');


EDIT:

OK. I think it's solved now! :)
Link to comment
Share on other sites

If you have control over the input string values, then put it in a better format making it easier for you to manipulate. This could be done in a few ways (like using preg_split), but here's a quick example of one way:
[code=php:0]

$mystring = "[name][age][pet][mike][22][dog][john][25][cat][kim][26][bird][pam][18][fish]";

$ary = explode(',', str_replace(array('[',']'), array('',','), $mystring));
array_pop($ary);  // Remove last blank entry

if (1 == (count($ary) % 3)) {
    exit('Error: Data not in multiples of 3');
}

$key1 = array_shift($ary);  // name
$key2 = array_shift($ary);  // age
$key3 = array_shift($ary);  // pet

$people = array();

for($i = 0, $cnt = count($ary); $i < $cnt; $i += 3) {
    $people[] = array($key1 => $ary[$i], $key2 => $ary[$i+1], $key3 => $ary[$i+2]);
}

print_r($people);
[/code]

[quote]

Array
(
    [0] => Array
        (
            [name] => mike
            [age] => 22
            [pet] => dog
        )

    [1] => Array
        (
            [name] => john
            [age] => 25
            [pet] => cat
        )

    [2] => Array
        (
            [name] => kim
            [age] => 26
            [pet] => bird
        )

    [3] => Array
        (
            [name] => pam
            [age] => 18
            [pet] => fish
        )

)
[/quote]
Link to comment
Share on other sites

You want two things actually. You want to use a multi-dimensional array, such as $people[1][2]. This translates into row 1, column 2. You will have three columns: name, age, and pet. The great thing with php is you can use number or associative keys for you arrays. In fact I think you can even use a combination of the two. In this case you could access it like so in a loop, $people[$key]['name'].

The second thing you want is the implode and explode functions. Implode is for taking an array and building a string with a common value separating the data. Explode is for taking a string with a common value separating the data and building an array of those values. So in the most basic case you have a string of comma separated values, you have a string called $stuff. Here is how you would use it:
$stuff = implode(',', $stuffarray);
$stuffarray = explode(',' $stuff);

I don't know if this function can be used for a multi-dimensional array like what you are doing, but it might.
[url=http://us3.php.net/manual/en/function.explode.php]http://us3.php.net/manual/en/function.explode.php[/url]
[url=http://us3.php.net/manual/en/function.implode.php]http://us3.php.net/manual/en/function.implode.php[/url]

-Patrick
Link to comment
Share on other sites

[code]<?php
$mystring = "[name][age][pet][mike][22][dog][john][25][cat][kim][26][bird][pam][18][fish]";
$mystring = replace("][",",",$mystring);
$mystring = replace("[","",$mystring);
$mystring = replace("]","",$mystring);
$myarray  = explode(",",$mystring);

for ($i=3; $i<count($myarray); $i+=3) {
   $people[] = array(
       $myarray[0] => $myarray[$i+0],
       $myarray[1] => $myarray[$i+1],
       $myarray[2] => $myarray[$i+2]
   );
}
?>[/code]
Link to comment
Share on other sites

Here´s yet another way

[code]<?php


$mystring = "[name][age][pet][mike][22][dog][john][25][cat][kim][26][bird][pam][18][fish]";



function toArray($name, $age, $pet) {
global $info;

$info[] = array('name' => $name, 'age' => $age, 'pet' => $pet);

}

preg_replace('/\[(.*?)]\[(.*?)]\[(.*?)]/e', 'toArray("\\1", "\\2", "\\3")', substr($mystring, 16));
print_r($info);

?>[/code]
Link to comment
Share on other sites

[code]
<?php
$mystring = "[name][age][pet][mike][22][dog][john][25][cat][kim][26][bird][pam][18][fish]";

$match = preg_match_all('/(\[[a-zA-z0-9]+\])+/iU',$mystring, $matches);
$j = -1;
$people = array();
$matches = str_replace("[","", $matches[1]);
$matches = str_replace("]","", $matches);
$i = 3;
while($i<count($matches)){
  $j++;
  $people[$j] = array(
      $matches[0] => $matches[$i],
      $matches[1] => $matches[$i + 1],
      $matches[2] => $matches[$i + 2]
      );
  $i += 3;
}
echo "<pre>";
echo $people;
print_r($people);
echo "</pre>";
?>
[/code]

This is what I copied from my browser:
[quote]
ArrayArray
(
    [0] => Array
        (
            [name] => mike
            [age] => 22
            [pet] => dog
        )

    [1] => Array
        (
            [name] => john
            [age] => 25
            [pet] => cat
        )

    [2] => Array
        (
            [name] => kim
            [age] => 26
            [pet] => bird
        )

    [3] => Array
        (
            [name] => pam
            [age] => 18
            [pet] => fish
        )

)
[/quote]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.