0

My data variable is following:

 canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4

I need it to transform to an array which should look following:

$arr = array(
"canv" => array("2", "3", "4", "5"),
"canp" => array("2", "3", "4"),
"canpr" => array("2", "3", "4"),
"canpp" => array("2", "3", "4"),
"all" => array("2", "3", "4")
);

Can you help me?

4 Answers 4

1
$data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";
$result = array();
foreach (explode(':::', $data) as $line) {
    list($part1, $part2) = explode(' = ', $line);
    $result[$part1] = explode(',', $part2);
}
3
  • Thank you. But now, I want to read if the key exist in the array this way: if(isset($result["canv"][$gid])) (where $gid is group id that is in the array), but it's not working because array looks like this: array("canv" => array(1 => "2", 2 => "3", 3 => "4", 4 => "5"); I need it to look like this: array("canv" => array("2", "3", "4", "5"); How can it be done?
    – Lucas
    Sep 26, 2011 at 20:31
  • if (isset($result['canv']) && in_array($gid, $result['canv']))
    – nachito
    Sep 26, 2011 at 20:45
  • You can't make the array look exactly like array("2", "3", "4", "5"), there must be indexes.
    – nachito
    Sep 26, 2011 at 20:52
1

The following should do the trick:

$data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";
$items = explode(":::", $data);
$arr = array();
foreach($items as $item) {
    $item = explode(" = ", $item);
    $arr[$item[0]] = explode(",", $item[1]);
}
1
  • Thank you. But now, I want to read if the key exist in the array this way: if(isset($result["canv"][$gid])) (where $gid is group id that is in the array), but it's not working because array looks like this: array("canv" => array(1 => "2", 2 => "3", 3 => "4", 4 => "5"); I need it to look like this: array("canv" => array("2", "3", "4", "5"); How can it be done?
    – Lucas
    Sep 26, 2011 at 20:33
0
$orig_str = 'canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4';

$parts = explode(':::', $orig_str);

$data = array()
foreach($parts as $key => $subparts) {
    $data[$key] = explode(',', $subparts);
}
1
  • 1
    Woops...right. Ah well, I'll take the math textbook way out and say that it's left as an exercise to the reader.
    – Marc B
    Sep 26, 2011 at 20:06
0

I would try something like this: this is not tested, try to print_r to debug

$string = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4";

$pieces = explode(':::',$string);
$result = array();
foreach($pieces AS $piece)
{
   $tmp = explode(' = ',$piece);
   $result[$tmp[0]] = explode(',',$tmp[1]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.