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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
if (isset($result['canv']) && in_array($gid, $result['canv']))
You can't make the array look exactly like array("2", "3", "4", "5"), there must be indexes.
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 Comment

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?
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 Comment

Woops...right. Ah well, I'll take the math textbook way out and say that it's left as an exercise to the reader.
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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.